Search code examples
reactjsstatesetstate

Deconstructed state is not updated even in the setState callback


Having an issue whereby deconstructing a component's state is preventing it from being updating within setState:

state = {
   value: 'test',
   values: ['a', 'b', 'c'],
};

...

const { value, values } = this.state;

this.setState(
  {
    values: [...values, value],
  },
  () => {
    console.log(values);
    // this logs ["a", "b", "c"] rather than ["a", "b", "c", "test"]
  }
);

The expected output of values should be with the new value included but it only logs the old values. Using "this.state" works so just wondering why deconstructing the state object doesn't seem to update properly?

You can go to this Codesandbox and give it a try yourself if you click on the button and check the console logs.

Any help on this would be much appreciated!


Solution

  • Assume the following:

    state = {value: 0}
    foo = () =>{
        const { value } = this.state
        this.setState({value : value + 1}, () => console.log(value)) //0
    }
    

    This is happening cause value holds the state value from when the method foo() was called, even after the state's update the value of this const won't change cause it's equivalent to: const value = this.state.value. It's a reference of what this value used to be. Use the global instance of state in this case to get access to the updated value

    this.setState({value : value + 1}, () => console.log(this.state.value))//1