Leon Leon - 2 months ago 14
React JSX Question

Issue with setState() in if statement

setState() in if statement:

// morePage = true
// pageNum = 1

if(morePage){
this.setState({pageNum: this.state.pageNum+1})
}

console.log(this.state.pageNum); // return: 1


setState() out if statement:

// morePage = true
// pageNum = 1

if(morePage){
// ...
}
this.setState({pageNum: this.state.pageNum+1})

console.log(this.state.pageNum); // return: 2


I'm facing that right now and I would like to know why...

Thanks :)

EDIT AFTER CORRECT ANSWER:

So yeah I should spend more time reading React's Doc :P
If someone is interested in knowing how I finally did, here is the answer:

In the docs, they say there is no guarantee that your state will have its new value before re-rendering. So you have to use "componentDidUpdate()".

So what I did is, I put the:

this.setState({pageNum: this.state.pageNum+1})


inside a random function I've created, after that in the "componentDidUpdate(prevProps, prevState)" function I can access the new and the old props values, and there I can use the previous and the current value of "pageNum" :)

Answer
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

As mentioned it is not guaranteed that the state value will be updated in your next line of code.

If you want to check the state for debugging try logging it in render method, as this method is invoked after the state is updated