0

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");
    };
Luis Kcomt
  • 61
  • 1
  • 1
  • 3
  • `this.setState` is asynchronous, the changes are not available instantly but after some time. If you want to read the same data you have just set you need to use the second `this.setState` argument. https://reactjs.org/docs/react-component.html#setstate – zerkms Jun 22 '20 at 03:28

4 Answers4

1

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

Zevgon
  • 556
  • 4
  • 13
1

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");
    });
};
Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18
1

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");
        });
    };

Marik Ishtar
  • 2,899
  • 1
  • 13
  • 27
1

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");
};
Dilan
  • 185
  • 1
  • 9