I cannot use a value saved in the state of React

Asked

Viewed 74 times

1

I created a button that receives a value, by clicking on it the value is stored in the state, soon after I try to get that state value but empty lap, the interesting thing is that in the second click on the button it returns the value of the first click.

The value of target does not serve, because I need to play the pro state value so that another function can be executed in sequence.

How do I fix it?

  eventToState = event => {
    this.setState({ buttonValue: event.target.value });
    console.log("teste", this.state.buttonValue);
  };

// SAÍDA
// teste "" 
// teste I'm the value of button element 

Entire code https://codesandbox.io/s/state-8fj2x

2 answers

4

It turns out that the method setState acts asynchronously (and does not accept async await, only callback). So he ends up changing the value of buttonValue after the call of console.log.

To solve this, you can use a callback which will be executed after the status value is changed:

this.setState({ buttonValue: event.target.value }, () => {
    console.log("teste", this.state.buttonValue);
});
  • @Augustovasques Sorry, it’s a friend of mine ^^

  • 1

    @Augustovasques quiet, you did not know, and incidentally here is not a "personal social network" so it was worth the tip yes!

3


The problem is that setState is asynchronous within Event handlers. This means that the state is being defined but cannot be accessed through this.state synchronously. There are two sessions of the documentation that explain this phenomenon. See here and here.

You can solve this problem by passing a callback as a second argument for the setState or calling the method this.test passing the value you set in the state as argument, since this is all done in the same function.

Then passing the callback at the setState:

eventToState = (event) => {
  this.setState({ buttonValue: event.target.value }, () => {
    this.teste();
  });
};

teste = () => {
  console.log('Teste:', this.state.buttonValue);
};

Or calling the method teste passing as argument the value you have just set to the state:

eventToState = (event) => {
  const newState = event.target.value;

  this.setState({ buttonValue: newState });
  this.teste(newState);
};

teste = (newState) => {
  console.log('Teste:', newState);
};

To learn more, see API of setState.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.