kayak
kayak

Reputation: 438

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;

Upvotes: 0

Views: 1530

Answers (2)

TopW3
TopW3

Reputation: 1527

Please try this. class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        checked: ""
    };
}

handleChange = (event) => {
    console.log("this.state", this.state); // Gets previous value
    this.setState({
      checked: event.target.value
    });
}

render() {

    return (
        <div className="wrapper">
            <input name="radioValue" type="radio" value="aaa"
                checked={this.state.checked === 'aaa'}
                onChange={this.handleChange} />
                First Radio Button
            <br />
            <input name="radioValue" type="radio" value="bbb"
                checked={this.state.checked === 'bbb'}
                onChange={this.handleChange} />
                Second Radio Button
        </div>
    );
}

}

It works well on my machine.

Upvotes: 0

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

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

you can also check like this by using callback in setstate

Upvotes: 1

Related Questions