Reputation: 637
I have the following code:
componentDidMount () {
fetch('/data')
.then(res => res.json())
.then(data => this.setState({data}));
this.countVar();
}
countVar () {
//iterate through this.state.data and filter out certain values
}
The countVar()
function isn't loading inside componentDidMount()
. When I did console.log(this.state.data)
right after the componentDidMount()
-function, it returned an empty array, so I guess that's the reason.
I tried to use componentDidUpdate()
instead if countVar()
, but I didn't consider that that would create an infinite loop. I don't quite know how to handle this.
The data that I'm fetching consists of several object arrays. in countVar()
I'm filtering out a certain object array, hence the structure of my functions.
Does anyone know how I could solve this problem?
Upvotes: 1
Views: 443
Reputation: 10307
You should call this.countVar inside the then of the Promise otherwise it will run before the fetch Promise is over.
Like this:
componentDidMount () {
fetch('/data')
.then(res => res.json())
.then(data => {
this.setState({data}, this.countVar);
});
}
I'm running this.countVar as a callback to setState so that it runs once setState is done.
Upvotes: 1
Reputation: 27346
fetch('/data')
.then(res => res.json())
.then(data => this.setState({data}));
This code is async. This means that when the fetch is complete, it will run the functions passed into the then
callback. You're running your iteration function directly after registering the promise; not after the promise is resolved.
ALSO
this.setState
is not synchronous. You can't guarantee that after you request that the state is set, it is set. It is set some time afterward, but React provides an option for this; you pass in a callback function once state setting is complete.
this.setState({ data }, () => console.log('do something'))
Upvotes: 4