Search code examples
reactjsuser-interfacestatedropdown

React Dropdown List - Selected Values Off By One


I have a dropdown list in React that is populating with data from my api, that works fine. Howver, when I select an option in the dropdown list, and i log the result, the result it logs always shows the item that's 1 place above the item I selected. It also shows as blank the first time I select, but then every select after that, off by one. Does anyone see what I'm missing?

import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';


class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = { 
            content: '',
            policy: '',
            policies: []
         };

        this.selectPolicy = this.selectPolicy.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy/all`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                this.setState({policies: result});
            });
    }


    selectPolicy(e) {
        this.setState({policy: e.target.value});
        console.log(this.state.policy);
    }

    render() {
                return (
            <div>
                <div className="container">

                    <select onChange={this.selectPolicy}
                            value={this.state.policy}>
                        <option default>Select Policy...</option>
                        { this.state.policies.map(item => (
                            <option key={item.policy}>{item.policy}</option>
                        ))}
                    </select>

                </div>
            </div>
        )
    }
}

export default TinyEditor;

Solution

  • Your console is getting rendered before completing a setSstate, Try the following code

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

    Here the console.log() will be called only after completing the setState.