VWang
VWang

Reputation: 193

How to get value of selected option in react-bootstrap select FromControl

I'm trying to write what the user selects from a dropdown to a firebase database based off the value stored in the component state, but I can't figure out how to get the value of the selected option and update it to the storeType state

Here is my dropdown menu:

<FormGroup>
                        <FormControl
                            componentClass="select"
                            placeholder="Store type"
                            onChange={this.handleCatChange}
                        >
                            <option value="placeholder">Choose eatery type...</option>
                            <option value="cafe">Cafe</option>
                            <option value="bakery">Bakery</option>
                            <option value="pizza">Pizza store</option>
                            <option value="sushi">Sushi store</option>
                            <option value="buffet">Buffet</option>
                            <option value="donut">Donut store</option>
                            <option value="other">Other</option>
                        </FormControl>
</FormGroup>

this.handleCatChange:

handleCatChange(e) {
    this.setState({
        storeType: e.target.value
    })
    console.log(this.state.storeType)
}

Upvotes: 1

Views: 3549

Answers (2)

Anupam Agnihotri
Anupam Agnihotri

Reputation: 292

you need to bind your function like this ..

 onChange={this.handleCatChange.bind(this)}



    constructor () {
        super();
        this.state = { 
          storeType: '' 
        };
      }


    handleCatChange(e) {
    const type = e.target.value;
        this.setState({
            storeType:type 
        });

    }

Upvotes: 1

Adrien Lacroix
Adrien Lacroix

Reputation: 3612

Your state is valid, but not when you do your console.log. It's because setState is asynchronous and does not mutate immediately your state values.

According to the docs,

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you need to ensure ordering of events after a setState call is made, you can pass a callback function.

this.handleCatChange

handleCatChange(e) {
    this.setState({
        storeType: e.target.value
    }, () => console.log(this.state.storeType))
}

Upvotes: 3

Related Questions