-1

I'm using CodePen for a ReactJS project. I need to set the localStorage for a part of the state that is:

this.state={
    Things:{
        element:"value",
        element2: "value"
    },
    activated:-1
}

Since I need to set only Things I decided to set the localStorage in the component lifecycle: componentDidUpdate()

componentDidUpdate(prevProps,prevState){
    localStorage.setItem("myThings",JSON.stringify(this.state.Things));
}

Here if I call console.log(localStorage.getItem("myThings")) I don't get any stored value.

For the localStorage checking part I implemented a solution in the constructor because I read in the React documentation that one should prefer the constructor to the componentWillMount() method (although I tried the latter too).

constructor(props){
    super(props);
    if (localStorage.getItem("myThings")!==null){
        this.state={
            Things:JSON.parse(localStorage.getItem("myThings")),
            activated:-1
        }
     }
     ...
Alessandro Carrese
  • 121
  • 1
  • 2
  • 14

3 Answers3

0

setItem is a function:

componentDidUpdate(prevProps,prevState){
    localStorage.setItem("myThings",JSON.stringify(this.state.Things));
}
Alex Borodin
  • 1,555
  • 12
  • 26
  • Additionally, if you need to store more complex data structures, see this answer: https://stackoverflow.com/a/2010994/2549154 – Wolfie Aug 04 '17 at 15:58
0

As stated from above setItem is a function. You may also need to access localStorage on the window obj.

window.localStorage.setItem(...);

or make a variable for it and reference that for a shorthand.

const storage = window.localStorage;
storage.setItem(...);
Alexg2195
  • 605
  • 7
  • 18
0

Error from distraction. The problem was the missing else in the constructor after the if(...){...} statement. so it was setting every time the next state after the state set in the if statement.

Thank you everyone.

Alessandro Carrese
  • 121
  • 1
  • 2
  • 14