Hiago Bonamelli
Hiago Bonamelli

Reputation: 381

React - setState does not update the value

I am trying to update the state with a localStorage value in DidMount, but it is not updating:

type Props = {
};

type State = {
    id_evaluation: string,
};

class Evaluation extends Component < Props, State > {
    state = {
        id_evaluation: '',
    }

    componentDidMount() {
        const id_eval = getEvaluation();
        console.log('1 - ', id_eval)

        this.setState({
            id_evaluation: '1',
        });

        console.log('2 - ', this.state.id_evaluation)

In the first console.log I have the value 1, in the second it remains empty, it does not update the state.

Upvotes: 0

Views: 494

Answers (3)

Sahil Raj Thapa
Sahil Raj Thapa

Reputation: 2473

setState works asynchronously so pass console.log as callback to get updated state.

this.setState({ id_evaluation: '1'}, () => console.log('2- ', this.state.id_evaluation));

when used as your code, console.log('2 - ', this.state.id_evaluation) is printing previous state not the updated state.

Upvotes: 2

prabin badyakar
prabin badyakar

Reputation: 1726

this.setState is an async function.

 this.setState({
        id_evaluation: '1',
 }, () => console.log('2 - ', this.state.id_evaluation));

Callback function would solve your problem.

Upvotes: 1

Joshua Obritsch
Joshua Obritsch

Reputation: 1293

That is because you call console.log before the state has updated. Try this:

this.setState({
  id_evaluation: '1',
}, () => {
  console.log('2 - ', this.state.id_evaluation);
});

See this thread:

Can I execute a function after setState is finished updating?

Upvotes: 3

Related Questions