简体   繁体   中英

React-select value set to null on first selection

I'm building a dropdown using react-select : https://react-select.com/home

My options for the dropdown are coming from a API call to a list. The issue I'm having is when you first select an option my AccountSelected1 says it's still null when I select another option than it starts to store in my AccountSelected1 state. However what it ends up storing is the previous selected option.

AccountSelected1: any,

AccountSelected1: null,

handleChangeAccountSelected1 = AccountSelected1 => {
    console.log(AccountSelected1);
    this.setState({ AccountSelected1: AccountSelected1.value}); 
    console.log(`AccountSelected1 set to:`, this.state.AccountSelected1); 
};  

public render(): React.ReactElement<WebappProps> {

    const { AccountSelected1 } =this.state;
        <Select
            value={AccountSelected1}
            onChange={this.handleChangeAccountSelected1} 
            options={this.state.AccountList}
        />
    return (

    )
}

Here is my console. As you can see it begins to store the second time with the previous value

//Console for First selection
{value: "23422", label: "23422", Description: "Account for Jeff"}
GLAccountSelected set to: null

//Console for Second selection
{value: "68755", label: "68755", Description: "Account for Lou"}
GLAccountSelected set to: 23422

As you mentioned, you don't get the description. I think you should set the whole object into state, your handleChangeAccountSelected1 should look like this:

handleChangeAccountSelected1 = AccountSelected1 => {
    console.log('AccountSelected1 BEFORE',this.state.AccountSelected1);
    this.setState({ AccountSelected1 },() => {
        console.log('AccountSelected1 AFTER',this.state.AccountSelected1);
    }); 
};  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM