Skip to content

Change game without changing the games added before

Im consuming a json file with the some games. I want to add a new Game and the chooseGameToAdd() choose what game will be without changing the games added before

enter image description here enter image description here

Json file:

enter image description here

Code:

import { games as gamesJson } from './games.json';

const App: React.FC = () => {
  const [whichGameIsVar, setWhichGameIsVar] = useState(0);
  const [state, setState]: any = useState([]);
  let game = gamesJson[whichGameIsVar].game;

  function addGame() {
    setState([...state, game]);
  }

  function chooseGameToAdd() {
    setWhichGameIsVar(whichGameIsVar + 1);
  }

  const GamesParent = (props: any) => {
    return (
      <div color={game}>
        <div>{game}</div>
      </div>
    );
  };
  return (
    <div>
      {state.map((item: any) => (
        <GamesParent key={item.id}>{item}</GamesParent>
      ))}
      <button onClick={addGame}>Add a Game</button>
      <button onClick={chooseGameToAdd}>Choose Game To Add</button>
    </div>
  );
};

export default App;

Answer

The problem is you do not have an id in the JSON objects, but you use item.id as the key. If you were actually using typescript and not just javascript with any everywhere, you would probably have picked that up. Either add the id to the JSON, or use the index as they key (less good!).