1

I am having problems of receiving the data from a api fetch, I am guessing data might received after the console.log()?

How can I fix this?

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        console.log(data[0])
      })

This code return a object data straight away

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false})
      })
      console.log(this.state.api)

However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.

Help....

  • 1
    Setting state is asynchronous, hence if you try to console it immediately it is empty. More can be found here https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync – msapkal May 30 '20 at 08:23

2 Answers2

1

state is updated asynchronously. If you want to see the updated state immediately after updating it, pass a second argument to setState function which is a callback function which runs after the state has updated

this.setState({api: data[0] ,loading:false}, () => console.log(this.state))
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • Hi mate, thanks for helping, I am not only trying to see it, because its running asynchronously, when I am trying to print it to the the screen in render(), its undefined, how can I print it after its actually fullly loaded? – Vincent Ning May 30 '20 at 08:29
  • inside render function, check if `this.state.api` is defined and print it only if it is defined – Yousaf May 30 '20 at 08:31
  • Yeah, Now i got it, you are a legend bro! – Vincent Ning May 30 '20 at 08:36
1

you are trying to resolve a promise and the console log is likely to be executed before the promise returns, try to following code to fetch your data:

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false},() => console.log(this.state.api))
      });

This always executes the log line after setting the state.

Shamanou
  • 41
  • 4