React setState not Updating Immediately
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.
Calling setState()
in React is asynchronous, for various reasons (mainly performance). Under the covers React will batch multiple calls to setState()
into a single state mutation, and then re-render the component a single time, rather than re-rendering for every state change.
Fortunately, the solution is rather simple - setState
accepts a callback parameter:
checkPencil: () => { this.setState(previousState => ({ pencil: !previousState.pencil, }), () => { this.props.updateItem(this.state); });}
When you're updating your state using a property of the current state, React documentation advise you to use the function call version of setState
instead of the object.
So setState((state, props) => {...})
instead of setState(object)
.
The reason is that setState
is more of a request for the state to change rather than an immediate change. React batches those setState
calls for performance improvement.
Meaning the state property you're checking might not be stable.This is a potential pitfall to be aware of.
For more info see documentation here: https://facebook.github.io/react/docs/react-component.html#setstate
To answer your question, i'd do this.
checkPencil(){ this.setState((prevState) => { return { pencil: !prevState.pencil }; }, () => { this.props.updateItem(this.state) });}