hisusu32
hisusu32

Reputation: 447

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

Upvotes: 0

Views: 2433

Answers (1)

CevaComic
CevaComic

Reputation: 2104

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);
    }); 
};  

Upvotes: 1

Related Questions