mardi 23 avril 2019

React: State update delay

I'm trying to change state by checking radio button. When I check it, it updates the value only after I check the next radio button. If I click first radio button it won't change the state, and if I check the second one it updates state with the previously checked radio button's value. Can anyone help me fixing this?

class App extends React.Component {

    state = { checked: false, radioValue: '' }

    handleChange = (event) => {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        console.log("this.state", this.state); // Gets previous value

        this.setState({
          [name]: value
        });
      }

    render() {

        return (
            <div className="wrapper">

                       <input
          name="radioValue"
          type="radio"
          value="aaa"
          checked={this.state.radioValue === 'aaa'}
          onChange={this.handleChange} />First Radio Button

            <br />

        <input
          name="radioValue"
          type="radio"
          value="bbb"
          checked={this.state.radioValue === 'bbb'}
          onChange={this.handleChange} />Second Radio Button

            </div>
        );
    }
}

export default App;




Aucun commentaire:

Enregistrer un commentaire