-1

I am trying to create modular code in JS and having trouble passing a variable with values to another method within the same class. I see result as '' right now. Please help!

class foodApp {
  
  constructor() {
     this.getjsondata = ''
  }
  

  fetchData() {
      return fetch("https://jsonplaceholder.typicode.com/users")
        .then(response => response.json())
        .then(data => {
            const result = JSON.stringify(data);
            this.getjsondata = result;
      })
  }
  
 displayHTML() {
    return console.log(this.getjsondata)
  }

}

new foodApp().displayHTML();
theusual
  • 741
  • 2
  • 11
  • 24

2 Answers2

2

fetchData is an async function and it will return a promise. you have to handle the promise.

Try the below code.

class FoodApp {
  constructor() {
    this.getjsondata = "";
  }

  fetchData() {
    return fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(data => {
        const result = JSON.stringify(data);
        this.getjsondata = result;
      });
  }

  displayHTML() {
    return this.getjsondata;
  }
}

let foodApp = new FoodApp();

(async function() {
  await foodApp.fetchData();
  console.log(foodApp.displayHTML());
})();
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
0

If you want fetchData to always run with every instance, which I think you might, include the function contents inside the constructor instead of in a separate method. Otherwise when you first call displayHTML the fetch hasn't happened yet.

constructor() {
      fetch("https://jsonplaceholder.typicode.com/users")
        .then(response => response.json())
        .then(data => {
            const result = JSON.stringify(data);
            this.getjsondata = result;
      })
  }
Sydney Y
  • 2,912
  • 3
  • 9
  • 15