Seemax
Seemax

Reputation: 121

React state update step behind

This color picker works but one step behind. I've been using React 15.4.2. Is it an issue to be fixed in later versions? In case it's my fault, please, how to master "pending state condition"? Pen http://codepen.io/462960/pen/qrBLje Code:

let Input =  React.createClass({
  getInitialState(){
        return {
        today_color: "#E5D380"
    };
    },
  colorChange(e){
        this.setState({
            today_color: e.target.value
        })
        document.querySelector('html').style.setProperty('--base', this.state.today_color);
     },
  render(){
    return (<div>
           <input className="today_color" onChange={this.colorChange} type="color" defaultValue={this.state.today_color}/>
           </div>)
  }
}) 

Upvotes: 0

Views: 1524

Answers (1)

paqash
paqash

Reputation: 2314

The issue you are having is that once you call setState the component rerenders and this code isn't called again:

document.querySelector('html').style.setProperty('--base', this.state.today_color);

And the first time it is called, this.state.today_color is still the previous value.

What you should do is the following:

this.setState({
  today_color: e.target.value
}, () => document.querySelector('html').style.setProperty('--base', this.state.today_color));

This makes sure the setProperty gets called after setState is done and after you have the correct value in your state.

Edit: here's a working example.

Upvotes: 3

Related Questions