The last 'SetItem' is not saved and clears when the page is Refresh

Viewed 32

Every time you click on the arrow, the React state is saved in the localٍ storage But when you refresh the page, the value decreases 1 because the last change is not saved to the localٍ storage

If you modify several items, the problem will be in the last pressed item

The Code is here => https://codesandbox.io/s/solitary-currying-jb2gx?file=/src/App.js

1 Answers

You're calling serializing function setLocalStorage() before the state is updated with upvote. The setState function is asynchronous and the state updates are batched by React, thus it doesn't change immediately. You should call setLocalStorage() inside second parameter (a callback) of setState. Then at the time of calling it you will have correct state.

Like this:

upVote = (id, delta) => {
  this.setState(
    (e) => ({
      text: e.text.map((x) =>
        x.id === id ? { ...x, vote: x.vote + delta } : x
      ),
      time: this.state.time
    }),
    () => this.setLocalStorage()
  );
};

You could also just pass a function itself as a second parameter of setState:

...
   time: this.state.time
    }),
    this.setLocalStorage
  );
}
Related