0

I am trying to update the react state and then immediately add the new state to local storage as below

constructor(props) {
        super(props);
        this.state = {
            testState: "testValue"
        };
    }
testFunction = (test) => {
    this.setState({ testState: [...this.state.testState, test] });
    localStorage.setItem("dummy", this.state.testState.toString());
}

However, the state change is not reflecting when I call the local storage method.

As a result i am ending up storing old value in the local storage.

But when testFunction execution completes, the component is reloaded with the updated state.

Thanks in advance!

Sallu
  • 116
  • 7

1 Answers1

1

setState is async call it is not directly change the context of the state, but it tells the DOM it should render again, this time with new context for what you modified (state or prop). What you need to do is to move localStorage usage into componentDidUpdate, and only then its guaranteed that you gonna store the right information


     testFunction = test => this.setState({ testState: [...this.state.testState, test] })


     componentDidUpdate(prevProp, prevState) {
     // check testState has changed in last render
       if (prevState.testState != this.state.testState) localStorage.setItem("dummy", this.state.testState.toString());
   }
Hagai Harari
  • 2,767
  • 3
  • 11
  • 23