0

I have select menus and i am trying to change a value when i select an option using optionSelect method. When i first select an option, the value is not being updated in the console.log. It only changes from the second time. Not sure what I am doing wrong. Do i need to add something in the componentDidMount!

constructor(props) {
    super(props);
    this.state = {
        value : '',
    };
}

optionSelect(option){
    this.setState({value : option.target.value});
    console.log(this.state.value)
}

render() {
    return (
        <React.Fragment>
            <Select name="item"
                required={this.props.required ? 'required' : ''}
                defaultValue={this.state.value}
                onChange={e => this.optionSelect(e)}
            >
                <option disabled value="">{this.props.placeholder}</option>
                {
                    this.props.optionData && this.props.optionData.length ?
                    this.props.optionData.map(option => (
                        <option key={option.id} value={option.id}>
                            {option.name}
                        </option>
                    )) : null
                }                   
            </Select>
        </React.Fragment>
    );
}
Elichy
  • 548
  • 4
  • 17

1 Answers1

0

setState() in React is not synchronous. While you try to console.log the value. The value has not updated yet. If you want to console.log a value immediately after it changes, add a

componentDidUpdate(){
 console.log('Value', this.state.value)
}