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
}
}
...