Jasper
Jasper

Reputation: 2231

React - saving state to local storage

We are working on a program where some part of the state has to be persistent. Localstorage seems to be the perfect solution for many reasons, except for the part where we cannot get it to work.

At first the local storage always seemed to update on step behind the rest of the program, as if its was being supplied an older state. We tried - after consulting some tips from blogs - the following approach

We update the localstorage with the callback of the 'setState' call.

this.setState(
    {selection: this.state.selection.concat(shop_item) },
    () => {
      this.saveToLocal();
    }
);

The 'SaveToLocal' function is as follows:

saveToLocal() {
       const local = this.state.favourites;
       this.localStorage.setItem(‘saveFavorites’, JSON.stringify(local));
   }

Yet this code does not seem to supply any value to localstorage at all. Does anyone have an idea of what we are doing wrong?

Upvotes: 8

Views: 9326

Answers (1)

Gui Herzog
Gui Herzog

Reputation: 5615

You should use only localStorage not this.localStorage.

Also, I would remove your arrow function on the callback of setState as you do not pass any parameters to this.saveLocal().

It should be more readable in this way:

this.setState(
  { selection: this.state.selection.concat(shop_item) },
  this.saveToLocal
);

Upvotes: 5

Related Questions