Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState not Updating Immediately

I'm working on a todo application. This is a very simplified version of the offending code. I have a checkbox:

 <p><input type="checkbox"  name="area" checked={this.state.Pencil}   onChange={this.checkPencil}/> Writing Item </p> 

Here's the function that calls the checkbox:

checkPencil(){    this.setState({       pencil:!this.state.pencil,   });    this.props.updateItem(this.state); } 

updateItem is a function that's mapped to dispatch to redux

function mapDispatchToProps(dispatch){   return bindActionCreators({ updateItem}, dispatch); } 

My problem is that when I call the updateItem action and console.log the state, it is always 1 step behind. If the checkbox is unchecked and not true, I still get the state of true being passed to the updateItem function. Do I need to call another function to force the state to update?

like image 581
lost9123193 Avatar asked Jul 25 '16 00:07

lost9123193


People also ask

Why setState is not updating immediately in React?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

How wait for state to update React?

Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.

Does setState work immediately?

setState or useState do not immediately mutate the state but create a pending state transition. Accessing state immediately after calling the updater method can potentially return the old value.

Why should we not update the state directly React?

One should never update the state directly because of the following reasons: If you update it directly, calling the setState() afterward may just replace the update you made. When you directly update the state, it does not change this.


1 Answers

You should invoke your second function as a callback to setState, as setState happens asynchronously. Something like:

this.setState({pencil:!this.state.pencil}, myFunction) 

However in your case since you want that function called with a parameter you're going to have to get a bit more creative, and perhaps create your own function that calls the function in the props:

myFunction = () => {   this.props.updateItem(this.state) } 

Combine those together and it should work.

like image 146
Ben Hare Avatar answered Sep 28 '22 00:09

Ben Hare