Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
Jasper Avatar asked Feb 03 '18 23:02

Jasper


1 Answers

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
);
like image 90
Gui Herzog Avatar answered Oct 01 '22 10:10

Gui Herzog