user8951490
user8951490

Reputation: 843

React Native: Strange Issue With Updating State

I am using the code below:

makeRemoteRequest = () => {
    let items = []; 
    models.forEach(element => {  //models is an array of the list of models
        this.pushReports(element, items); 
    });
    console.log("This is the item array: ",items); 
    this.setState({
        data:items
    });
    console.log("This is the data in state: ",this.state.data); 
}

Somehow, the console log for the items array is showing me the array that I need, but the console log for the this.state.data is empty. How can this be possible? The log for the items array is run right before state is set.

This is preventing me from updating my state.

Upvotes: 0

Views: 75

Answers (3)

getumangon
getumangon

Reputation: 201

this.setState is rendering asynchronously. And you're trying to print in next line so it will not give immediate results as you want.

Solution: do this in next line,

setTimeout(() => {console.log("This is the data in state: ",this.state.data) }, 1000)

Upvotes: 1

Pir Shukarullah Shah
Pir Shukarullah Shah

Reputation: 4232

Since setState works in an asynchronous way. That means after calling setState the this.state is not immediately changed. So if you want to perform an action immediately after setting state, use 2nd argument as callback on setState. Consider this example:

this.setState({
    data: newData
}, () => {
  //TODO: Do something with this.state here
});

Upvotes: 1

Jpoliachik
Jpoliachik

Reputation: 2638

this.setState() does not run synchronously. Your state is not guaranteed to be updated on the next immediate line, but it will be updated properly on the next render cycle. Try putting console.log within render() and you'll see.

Discussion about this topic here: https://github.com/facebook/react/issues/11527#issuecomment-360199710

Upvotes: 1

Related Questions