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
Json file:
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;
Advertisement
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!).