Андрей Андрей - 1 year ago 88
React JSX Question

Why does not localStorage save the last symbol in this component?

In the code below, when I change the text of input the localStorage does not save the last symbol. As if I write qwerty, refresh and it gives only qwert.

let NameAndCity = React.createClass ({
getInitialState: function() {
return {
name: this.props.name,
city: this.props.city

componentWillMount: function() {
let username = localStorage.getItem('username')
let city = localStorage.getItem('city')
if(username && city){
name: username,
city: city
} else {localStorage.setItem('username', this.state.name)
localStorage.setItem('city', this.state.city)}

this.setState({name: e.target.value})
localStorage.setItem('username', this.state.name)

this.setState({city: e.target.value})
localStorage.setItem('city', this.state.city)

render(){return (
<div className='name-and-city'>
<input value={this.state.name} onChange={(e)=> this.changeName(e)}/>
<input value={this.state.city} onChange={(e)=> this.changeCity(e)}/>

Answer Source

This is a known issue. You are updating the state with onChange event. But you are using the this.state.name without setting the state. Since setState is async try to use the state value in a callback as follows.

   var _this = this;
   this.setState({name: e.target.value}, function(){
       localStorage.setItem('username', _this.state.name);


Simply use the event.target.value to store in localStoarge

    this.setState({city: e.target.value}); //here state.name != e.target.value
    localStorage.setItem('city', e.target.value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download