Андрей Андрей - 20 days ago 7
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){
this.setState({
name: username,
city: city
})
} else {localStorage.setItem('username', this.state.name)
localStorage.setItem('city', this.state.city)}
},

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

changeCity(e){
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)}/>
</div>
)}
})

Answer

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.

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

or

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

changeCity(e){
    this.setState({city: e.target.value}); //here state.name != e.target.value
    localStorage.setItem('city', e.target.value);
},