1

I have this array state :

  const [players, setPlayers] = useState([]);

I want every time I add a player, to add the new value in addition to the previous ones so I did this:

  const addPlayerHandler = (name) => {
    setPlayers({ players: [...players, name] });
  };

when I add the first value works fine, but the second value it gives me error : players is not iterable, when did arrays become uniterable ?

5 Answers 5

1

What's your data structure?

Like this?

[{ name: 'player 11',  }]

if above, try setPlayers({ players: [...players, { name }] });

Sign up to request clarification or add additional context in comments.

Comments

0

Players is an array, not an object, you can do: setPlayers( [...players, name] );

1 Comment

This gives the same error
0

Your setPlayers() assigns an object (with players as a key) as a value to the players variable.

Instead, what you are looking for is setPlayers(prevPlayers => [...prevPlayers, name])

So you need to assign an array instead of an object.

Comments

0

You can do something like this:-

 const [player, setPlayer] = useState({});
 const [players, setPlayers] = useState([]);

 const addPlayerHandler = (name,e) => {
    e.preventDefault();
    if (name.trim() !== "") {
        const newPlayer = {
          player_id: `p_${Date.now()}`,
          player_name: name,
       };
       const palyersList = [...players];
       palyersList.push(newPlayer);
       setPlayer({});
       setPlayers(palyersList);
     } 
     else {
       setPlayer({});
       console.log(`error`,"Invalid or Empty Player Details");
    }
  };

Comments

0

I had the same issue, it was because I used useEffect() on window load to set state to the JSON.parse(localStorage.getItem("array") so my array was essentially turning into an Object and that's why it was not iterable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.