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?
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With