1

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)
}
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Brian Thompson Jun 01 '21 at 14:59
  • Also see: https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately for the correct `setState` syntax to get log your updated value. – Brian Thompson Jun 01 '21 at 15:00
  • Can you show valueToState's definition? It will help us better understand what is happening. – Tushar Shahi Jun 01 '21 at 15:00
  • Thank you, sure: ``` // Save input values to current state valueToState = ({ name, value }) => { this.setState(() => { return { [name]: value }; }); }; ``` – Mike Henriquez Jun 01 '21 at 15:04

1 Answers1

1

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.