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

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

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?
inside render function, check if this.state.api is defined and print it only if it is defined
Yeah, Now i got it, you are a legend bro!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.