Home > Net >  react : array state is not iterable
react : array state is not iterable

Time:10-09

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 ?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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");
    }
  };
  • Related