Nick Maddren
Nick Maddren

Reputation: 583

React prop only changes state after selecting twice

I am using React Select and for some reason my state is only changing after an option has been selected twice.

I have the following code:

var React = require('react');
import Select from 'react-select';

class VehicleSelect extends React.Component {

  constructor(props) {
    super(props);

    this.state = { brandSelect: ""};

  }

  _onChange(value) {
    //console.log(value) - just to see what we recive from <Select />
    this.setState({brandSelect: value});
    console.log(this.state.brandSelect);
  }

  render() {
    var options = [
    { value: 'Volkswagen', label: 'Volkswagen' },
    { value: 'SEAT', label: 'SEAT' },
    { value: 'SKODA', label: 'SKODA' }
    ];


    return (
      <Select
          name="form-field-name"
          value={this.state.brandSelect}
          options={options}
          placeholder="Select a brand"
          searchable={false}
          onChange={this._onChange.bind(this)}
      />
    )
  }
};

// Export our component
export default VehicleSelect;

When one of the options is selected it won't console.log the new state however if I select the option again it will. Any idea where I am going wrong, I'm guessing because the state isn't being shown in the console.log it isn't updating?

Thanks

Upvotes: 1

Views: 1090

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

setState does not change state immediately. You need to use a callback. Docs.

_onChange(value) {
    //console.log(value) - just to see what we recive from <Select />
    this.setState({brandSelect: value}, () => {
        console.log(this.state.brandSelect);
    });
  }

Upvotes: 6

Related Questions