Home > Mobile >  Icon doesn't change on button toggle - React
Icon doesn't change on button toggle - React

Time:08-10

The FontAwesome icons won't update icon. The toggle has to happen onClick of the "Ready" button. The action takes place well and the state of the isReady property of the object changes values from FALSE to TRUE and reversed. Any ideas why the icons wont update as well?

    let [gameData, setGameData] = useState(props[1]);
    const toggleReady = (c) => {
    const newGameData = gameData;
    newGameData.clients[c].voteReady = !newGameData.clients[c].voteReady;
    setGameData(newGameData);
    console.log(gameData.clients[c].voteReady);
  };

   return (
    <div>
      <Header name="Waiting Room" />
      <div className="centered">
        <div className="players">
          <h1>Lobby players:</h1>
          {gameData.clients.map((c, index) => (
            <div>
              <div>
                <h2 key={c.id}>
                  Player {index   1}: {c.username}
                </h2>
                {c.voteReady === true ? (
                  <BsFillCheckCircleFill className="mark" />  
                ) : (
                  <BsXCircleFill className="cross" />
                )}
                {c.id === clientId ? (
                  <button
                    className="btn btn-info btn-sm button-ready"
                    onClick={() => toggleReady(index)}
                  >
                    Ready?
                  </button>
                ) : null}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

CodePudding user response:

Two things here what is happening is that you are mutating the state,

Use const for the useState since it should not be treated as a mutable value.

const [gameData, setGameData] = useState(props[1]);

Your function should create a clone of gameData, not just assign gameData to the new variable, you can use the spread operator to achieve this.

const toggleReady = (c) => {
 // Here you will create a copy of gameData and you'll not mutate the original.
 const newGameData = { ...gameData };
 newGameData.clients[c].voteReady = !newGameData.clients[c].voteReady;
 setGameData(newGameData);
 console.log(gameData.clients[c].voteReady);
};
  • Related