Setstate with onChange, Reactjs

Asked

Viewed 837 times

2

I brought a little problem that I am going through in an application that I am doing in React, I will replicate right here below.

STATE DECLARED IN COMPONENT

this.state = { estadoCivil: ''};

JS

onChange = e => {this.setState({[e.target.name]:e.target.value});
console.log(this.state);

JSX

 <div className="form-group col-12">
                <label>Estado Civil</label>
                    <select id="estado-civil" className="custom-select" name="estadoCivil"
                     onChange={this.onChange} required >
                        <option defaultValue>selecione uma opção</option>
                        <option value='solteiro'>Solteiro(a)</option>
                        <option value='casado'>Casado(a)</option>
                        <option value='viuvo'>Viúvo(a)</option>
                    </select>
                </div>

Guys, here’s my question, the above solution works, but whenever I change the value in select and runs the onChange function, it returns in the console the Civil state in the previous state, setState always seems to be late, never shows the value I change at the moment. Could anyone help? From now on, thank you very much.

1 answer

2

One should not rely on the "synchronicity" of setState no React, to show on the console, you should do something like:

onChange = e => {
  this.setState(
    {[e.target.name]: e.target.value},
    () => console.log(this.state)); //coloca o console no callback do `setState`
}

React state and your callback

This callback from the setState is called when the function is finished.

  • After observing a little more and taking a look at the documentation, I really realized that my mistake was more for lack of attention, thank you very much for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.