Suppose I have an input in my webpage. When a use enters a value, I want to keep the value for the future reloads of the page. Like if the use enters a value in the input and closes the page, I want to load the value, next time that the user loads the page. What is the best way to do this?
Asked
Active
Viewed 65 times
0
Daniel
- 5,839
- 9
- 46
- 85
-
Take a look at the [Web Storage API](http://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API). If you want to support
– rgajrawala Jul 19 '15 at 19:45 -
@usandfriends could you write your comment as an answer? – Daniel Jul 20 '15 at 18:27
-
Yes, but as a note, my comment does not go over React implementation of these APIs. See @Michael's [answer](http://stackoverflow.com/a/31518822/2006429) for that information. – rgajrawala Jul 20 '15 at 18:32
1 Answers
1
Here is what I came up with:
var Foo = React.createClass({
mixins : [React.addons.LinkedStateMixin],
getInitialState : function () {
if (localStorage.getItem('savedText')) {
return (
{savedText : localStorage.getItem('savedText')}
);
} else {
return (
{savedText : ''}
);
}
},
componentDidUpdate : function () {
localStorage.setItem('savedText', this.state.savedText);
},
render : function () {
return (
<div>
Enter some text, then refresh the page
<br/>
<input type='text' valueLink={this.linkState('savedText')} />
</div>
);
}
});
Explanation:
getInitialStateis used to check if the saved value in localStorage exists. If it does, it sets oursavedTextstate to whatever the value is - if it does not, it sets the state to an empty string.- The
LinkedStateMixinensures that thesavedTextstate is always equivalent to the value in the input. Thus,getInitialStateis actually setting the initial value of the input, and every time the input value changes, the state changes along with it. - Every time a state change is made (so every time the value in the input changes),
componentDidUpdateis called, which stores the current value back into localStorage.
I opted to use localStorage, which will save the value even if the browser closes, but if you are just interested in keeping the value after a page refresh, then sessionStorage will work just fine too.
Here is a demo of it working: http://output.jsbin.com/bayayikipi
Michael Parker
- 12,724
- 5
- 37
- 58