Mike Henriquez
Mike Henriquez

Reputation: 59

ReactJS state value not update correctly on input onChange

In my app, i have Groups, and i have a select input, to change between group lists. My issue is when i change the select input, the state changes the name of the list, but is not the one im selecting. For example, at initial i have:

All Groups Group #1 Group #2

When i choose Group #1, the state in the console says "All Groups". If i choose Group #2, the state in the console says "Group #1"

Select Input

<select id="selectedPg" name="selectedPg" onChange={event=> {
    this.valueToState(event.target)
    this.viewProfileGroup();                                        
}}>

viewProfileGroup()

// View Selected Profile Group
viewProfileGroup = ()=> {
    const {  selectedPg, allProfilesLists } = this.state
 
    this.setState({            
        profilesLists: allProfilesLists.filter(pg => pg.profileGroup === selectedPg)
    })

    console.log(this.state.selectedPg)
}

Upvotes: 1

Views: 301

Answers (1)

user9760669
user9760669

Reputation:

The issue is the setState is not synchronous, so when you call this.viewProfileGroup() and in the method, you are not operating on the latest state. The solution is simple. Just pass event.target to the viewProfileGroup function

this.valueToState(event.target)
this.viewProfileGroup(event.target); 

PS, maybe in this way you will do not need this.valueToState at all.

Upvotes: 1

Related Questions