Home > Blockchain >  React useState Dependency Won't Update When Same Value Passed
React useState Dependency Won't Update When Same Value Passed

Time:04-25

I'm trying to create a game using React hooks. Essentially you get given a football players career history and you have to guess which player it is.

I'm having an issue though, because on rare occasions you might guess a player for e.g 'beckham' and then the next player generated may have the same name 'beckham' but be a completely different player just ironically has the same name.

My issue is I have a useEffect with a dependency of guess e.g 'beckham' and then some code runs to check the answer.

But if you have a player with an indentical surname again on the next player and guess 'beckham' again then the check answer code never runs because the useEffect looks at the guess dependency and says it's the same as before I'm not running the code inside.

Codepen example

https://codepen.io/joe-consterdine/pen/popmNrE

Here the useEffect will never rerender because 'joe' is always the guess, but in the game there's two joes so it's not the same person.

Thanks

  const [players, setPlayers] = React.useState([
    {
      id: 0,
      name: 'joe'
    },
    {
      id: 2,
      name: 'joe'
    },
  ]);
  const [guess, setGuess] = React.useState('joe');
  
  const handleOnSubmit = (event) => {
    event.preventDefault();
    // setGuess('james');
    setGuess('joe');
  }
  
  React.useEffect(() => {
    console.log('re rendered');
  }, [guess])

  return (
    <div>
      <form onSubmit={handleOnSubmit}>
        <input type="text" />
        <button type="submit">Submit</button>
      </form>
      {players.map(player => (
          <p key={player.id}>{player.name}</p>
      ))}
    </div>
  );
}

CodePudding user response:

I would change the string state with object state. With this solution you will not have same problem

const [guess, setGuess] = React.useState({id: 0, name: 'joe'});
  • Related