Update localStorage after setState - React

Update localStorage after setState - React
0

#1

I am trying to set localStorage equal to current state after it is updated. Unfortunately, I notice that localStorage set to prevState value. Is there any way to make sure localStorage updates after setState?

markDone (i){
        var array = this.state.tasks;
        array[i].done = true;
        this.setState((prevState) => {
          return {tasks: array,
          completedCount: prevState.completedCount + 1};
        });
   localStorage.setItem('doneTasks', JSON.stringify(this.state.completedCount));
      }

Thank you for any help!


#2

setState is async i believe - maybe try something like this…

        this.setState((prevState) => {
          return {tasks: array,
          completedCount: prevState.completedCount + 1};
        }).then(() => {
          localStorage.setItem('doneTasks', JSON.stringify(this.state.completedCount));
      });

not sure


#3

I have some months without working with React but if a remember good, the setState method is asynchronous so you have to wait until the component is updated. That’s why the React component class have life cycle methods.

In this case I guess you can do this:

markDone (i){
  var array = this.state.tasks;
  array[i].done = true;
  this.setState((prevState) => {
    localStorage.setItem('doneTasks', JSON.stringify(prevState.completedCount + 1));
    return {
      tasks: array,
      completedCount: prevState.completedCount + 1;
    }
  });
}

#4

I think the best method for this is using the built in componentDidUpdate method. Does as the method is named, when your component renders from a prop/state change it’s going to be called.

Here’s an example from the react course I’ve been doing.

 componentDidUpdate(prevProps, prevState) {
    if (prevState.options.length !== this.state.options.length) {
      const json = JSON.stringify(this.state.options);
      localStorage.setItem("options", json);
    }
  }

#5

As everyone else here said, setState is asynchronous, but luckily for us the function accept a callback

from react documentation:

setState(updater[, callback])

This means that you can simply write your function as:

this.setState(
{ someSate: obj}, //updater
() => { localStorage.setItem('...') } // callback
);

#6

@moT01, @ejas94, @GeeLie, @Marmiz thank you very much for your help and solutions! Problem is solved :slight_smile: