G-Man
G-Man

Reputation: 7241

how to deal with asynchronous nature of setting state with hooks

I have the following pseudo code and my issue is that since setting the state is asynchronous, by the time the state is done updating, the event has already been fired twice and I end up with duplicate objects in my state

const userList [ userList, setUserList ] = useState([]);

const onEvent = (user) => {
    //then event fires again but previous setUserList has not finished setting the state
    //so it is not found in userList and then I find myself with 2 of the same users in the list

   if (userList.findIndex(u => u.name=== user.name) === -1)
      setUserList(userList=> [...userList, {name:user.name}]);
}

Upvotes: 0

Views: 68

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

The callback function for setUserList gives you the most recent value of the userList. So perform your check inside the function, not outside of it.

setUserList(previous => {
  if (previous.findIndex(u => u.name === user.name) === -1) {
    return [...previous, { name: user.name }];
  }
  return previous; // Since this line does not change the state, the component will not rerender
});

Upvotes: 3

Related Questions