Reputation: 61
I've read in many places that I shouldn't use this.state, but this.setState instead; the problem is that it won't work for my code. What am I doing wrong?
What I'm doing that works
submitForm = () => {
this.state.isAuthenticated = true
this.setState({
isAuthenticated: true,
userName: this.state.userName,
});
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
};
What doesn't work for some reason
submitForm = () => {
this.setState({
isAuthenticated: true,
userName: this.state.userName,
});
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
};
Upvotes: 0
Views: 56
Reputation: 195
The other answers explain how this.setState is asynchronous. To address your question on why this.state doesn't work: this.state is only accessing the value of the state. You cannot set the state like you would set another variable. You need to use this.setState.
Also an alternate solution would be to simplify your code since isAuthenticated is known to be true:
submitForm = () => {
this.setState({
isAuthenticated: true,
});
this.props.onLogIn(true, this.state.userName);
this.props.history.push("/predict");
};
Upvotes: 1
Reputation: 3049
use the setState callback
submitForm = () => {
this.setState((state) => ({
isAuthenticated: true,
userName: state.userName,
}), () => {
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
});
};
Upvotes: 1
Reputation: 2227
setState is asynchronous, so when you do this.props.onLogIn, the value in state has not updated without one render .check in your second argument of setState like this.
submitForm = () => {
this.setState({
isAuthenticated: true,
userName: this.state.userName,
}, () => {
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
});
};
Upvotes: 1
Reputation: 644
setState
is asynchronous, so by the time you do this.props.onLogIn
, the value in state has not updated yet. You need to do run those last couple lines in the callback of setState. See When to use React setState callback
Upvotes: 1