Aphorism44
Aphorism44

Reputation: 87

Why is React fetch ignoring the JSON data I'm getting?

I am teaching myself how to "fetch" data within React. However, although I am able to grab the JSON data from a local file, it somehow disappears when I try to place it into the component's state.

I am using the following tutorial. The precise code I'm copying is the second image at this link:

https://www.robinwieruch.de/react-fetching-data/#react-how-fetch-data

For example, the below code, in the log, returns the correct data:

constructor(props) {
  super(props);
  this.state = { cardData: [] };
}

componentDidMount() {
   fetch(cardDataJsonLocation)
    .then(response => response.json())
    .then(data => console.log(data.cardData));
} 

When I look at the console in my browser, the correct data is being logged - an array with 2 objects in it:


[{…}, {…}] 0: {name: "dom", id: 1} 1: {name: "dave", id: 2}
length: 2 __proto__: Array(0)

However, when I change the above code to actually place the above array data in my component's state:

componentDidMount() {
fetch(cardDataJsonLocation)
  .then(response => response.json())
  .then(data => this.setState({ cardData: data.cardData }))
  .then(console.log(this.state));
}

When I log the state, there's no change from the original state I set in the constructor.

In this case, it logs an empty array. If I set the state (in the constructor) to, say, [1,2,3] or null, then that value comes down instead.

Am I missing a step in the fetch process? It's as if it skips the step where I try to setState after fetch. Thanks.

Upvotes: 1

Views: 211

Answers (1)

Guilherme Lemmi
Guilherme Lemmi

Reputation: 3487

As others have pointed and as described in the documentation, setState() is an async method.

If you need to access the state immediately after calling setState, then put your code in a callback and pass this callback as the second parameter of setState, like in:

this.setState({ cardData: data.cardData }, () => { console.log(this.state); })

Upvotes: 3

Related Questions