#Updating/Reloading React component on button press

1 messages · Page 1 of 1 (latest)

crimson nebula
#

Hey all!

I have a simple Hockey game I'm working on for my Dad. Here's some of the code I'm trying to wrangle into having a "replay" button / feature:

const Results = ({ setScene, teams, teamData }) => {
  const visitors = teamData.filter(team => team.name === teams.visitors)[0];
  const home = teamData.filter(team => team.name === teams.home)[0];

  const game = new Game(visitors, home);
  game.play();

  return (
    <>
      <Header game={game} />
      <BasicScore game={game} />
      <BoxScore game={game} />
      <PlayByPlay game={game} />

      {/* TODO: Add replay button */}
      <button onClick={() => game.play()}>Replay</button>
      <button onClick={() => setScene("main")}>Menu</button>
    </>
  );
};

**Expected behavior: ** Clicking the replay button should update the values for the game object, and update the display oif them.
Actual behavior: The game data/object is updating, but it's not being re-rendered out down through the other components.
My attempts: Since a component re-renders when its state is updated, I tried storing the game in state and then resetting it after game.play() but it did not seem to make a difference.

Tl;dr: How can I force this change to propagate? Thanks for any and all help!

#

useState version of the code:

const Results = ({ setScene, teams, teamData }) => {
  const visitors = teamData.filter(team => team.name === teams.visitors)[0];
  const home = teamData.filter(team => team.name === teams.home)[0];

  const [game, setGame] = useState(new Game(visitors, home).play());

  return (
    <>
      <Header game={game} />
      <BasicScore game={game} />
      <BoxScore game={game} />
      <PlayByPlay game={game} />

      {/* TODO: Add replay button */}
      <button onClick={() => setGame(game.play())}>Replay</button>
      <button onClick={() => setScene("main")}>Menu</button>
    </>
  );
};
prisma sky
crimson nebula
#

I have never looked at Memo! I will do so now haha

prisma sky
#

The new React beta docs are really nice and have exercises in them. Highly recommend going through them even as a refresher.

crimson nebula
#

Figured it out, React checks dependency change by using Object.is comparison. I wasn't changing the object, just updating some of it's values, so I changed the onClick to create a new object and now things are updating!

prisma sky
#

I apologize, I don't think I understood the stated problem correctly. Hope I didn't confuse you, and glad you figured out a solution!