Issue
I am a beginner in react, but I have already searched in several places and I can't solve. My problem is change the value of variable in react native, basically I need create a function to set a variable with true or false, but when I try use the variable, it always is false.
In the constructor:
this.state = {
uid: "",
name: "",
email: "",
pass: "",
loading: false
};
The function is call for the button:
setLoader = () => {
console.log(this.state.loading);
this.setState({ loading: !this.state.loading });
console.log(this.state.loading);
};
The exit of console is:
[19:52:10] false
[19:52:10] false
Solution
That is because setting state is an asynchronous task. It takes time for it to set. If you try and call the value like you have done you will find that it hasn’t updated, this is expected behavior.
If you want to find out the value in state after you set it you should do the following
this.setState(previousState => {
return { loading: !previousState.loading }
}, () => console.log(this.state.loading));
setState takes a callback, which is called once the state has been set
Check out these three awesome articles that describe state
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
Answered By - Andrew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.