'react : array state is not iterable
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 ?
Solution 1:[1]
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.
Solution 2:[2]
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");
}
};
Solution 3:[3]
What's your data structure?
Like this?
[{ name: 'player 11', }]
if above, try setPlayers({ players: [...players, { name }] });
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gpopides |
| Solution 2 | Arnab_Datta |
| Solution 3 | tomoe |
| Solution 4 | Marina Kim |
