Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LocalStorage with React?

From what I am experiencing so far, it doesn't seem like ReactJS updates with the state of localStorage. My code below.

var Frr = React.createClass({ getInitialState: function(){ return { lights: localStorage.getItem('state')} },  switchoff: function(){ this.setState({lights: localStorage.setItem('state', 'off')});  },  switchon:function(){ this.setState({lights: localStorage.setItem('state', 'on')});  },  render:function(){ if (this.state.lights === 'on'){ return ( <div> <p>The lights are ON</p> <input type="submit" value="Switch" onClick={this.switchoff}/> </div> );}  if ( (this.state.lights === 'off')|| (!this.state.lights) ){ return ( <div> <p>The lights are OFF</p> <input type="submit" value="Switch" onClick={this.switchon}/> </div> );}   } }); 

Simple application. If the state of localstorage is off or empty, then render the view with the ON button. If localstorage is on, then render the view with the OFF button.

I want to be able to set this render based on the state of localStorage. I have tried doing the same thing using basic booleans, and it works as expected. However, when using localStorage, something doesn't appear to work.

I wouldn't be surprised if my logic is simply off.

EDIT: To explain, the button and the view don't act as they should. When the lights are off and there is nothing in Storage, the button adds ON to localStorage, but does not change the view. If I refresh the page, the page renders ON, and when I click on it the button works by turning it OFF. But it only works once, which leads me to believe there may be a problem with the OFF switch.

like image 949
Jason Chen Avatar asked Jul 17 '16 15:07

Jason Chen


People also ask

Can I use localStorage in React?

How to Implement localStorage in React. localStorage provides us with access to a browser's storage object, which includes five methods: setItem() : This method is used to add a key and a value to localStorage. getItem() : This method is used to get an item from localStorage using the key.

How do I store multiple data in localStorage in React JS?

Here is "Post. const Posts = ({ posts, loading }) => { const click = (id, name, bio, link) => { //setButtonText(text); const obj = { id: id, name: name, bio: bio, link: link, }; localStorage. setItem('items', JSON. stringify({ ... obj })); }; if (loading) { return <h2>Loading...


1 Answers

The .setItem() local storage function returns undefined. You need to perform the local storage update and then return the new state object:

switchoff: function(){     localStorage.setItem('state', 'off');     this.setState({lights: 'off'});  }, 
like image 85
Pointy Avatar answered Sep 25 '22 07:09

Pointy