0

I want updated playerNames, so that I cant send it to reducer, but after setting state I am not getting the updated state, both in if and else condition

 const [playerNames, setPlayersName] = React.useState([]);

      let updatePlayers = playerNames.map(item=>item.id == event.target.value.id
        ? {...item}
        :item
        
        setPlayersName(updatePlayers)

    }else{
      setPlayersName(prev=>[...prev,event.target.value])
    }

    dispatch(selectPlayers(playerNames))

ASIF KAIF
  • 317
  • 1
  • 4
  • 17

2 Answers2

0

On the other hand, you can dispatch the data without setting the state. Just use event.target.value or a simple let variable = ..., and dispatch that instead. We use states to re-render components, there is no need to set the state if you are going to dispatch it.

Sobhan Jahanmard
  • 821
  • 5
  • 16
0

You can't really call the dispatch right after calling the selectPlayers hook.

Why In class based component, The setState has a callback function that can be executed right after the state update. But in terms of hook we do not have that. But we can achieve that with some tricks.

In your case I would something like this.

Solution At first I would define an useEffect and give the playerNames as a dependency So whenever the state gets changed it will call dispatch

useEffect(() => {
  dispatch(selectPlayers(playerNames))
}, [playerNames])

Why this useEffect It will give your more power to conditionally call the dispatch and execute it. We can also do it in many other ways like bellow.

dispatch(selectPlayers(updatePlayers))

Doc link - https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

moshfiqrony
  • 4,303
  • 2
  • 20
  • 29