-2

I wast trying to fetch some data in componentDidMount and then set it to state, wrote an async await function for the same. But if i was trying to set the state with the values right after await, the value was getting set to a pending promise but console logging would give the correct output. For that reason i called the getData().then() to set the data, why it was giving pending promise can someone clear the concept out here?

componentDidMount() {

    async function getData() {
      const baseUrl = `https://........`;
      const response = await fetch(baseUrl);

      if (response.status === 200) {
        const json = await response.json();
        const { data } = json;
        //console.log(data) =>correct output
        return data;
      }

      return null;
    }

    getData().then(data => {
      this.setState({ names: data });
    });
   
}
  • Before it resolves, any `async`expression, including promises, if read/logged, will output: promise with in a pending state. After it gets resolved/rejected, anything reading/logging it will return that result. Could you specify in more detail the part that is not clear? Reading [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) might help. – tao Jan 12 '22 at 15:36

2 Answers2

0

You can simply do it like that:

    componentDidMount() {
        const baseUrl = `https://........`;
        fetch(baseUrl)
        .then((response) => response.json())
        .then(result => {
            this.setState({ names: result.data});
        });
    }
Borni.Mr
  • 646
  • 3
  • 7
0

getData is an async function that you syncronize your fetch call inside. So it returns a promise. You're console logging inside that function after response fetched. So it logs the data.

You can think it as Fetch function that you use, you're awaiting it because it's a async function and you should await for the response. It's the same for the getData too. No matter how you wait, use then or await.

acbay
  • 832
  • 7
  • 7