I have a React component where I'm using the useState hook to manage an array. Initially, my state is defined like this:
const [rows, setRows] = useState([1]);
When I try to append a number to the array using a button click:
setRows([...rows, 1])
and iterate through the rows
:
rows.map((row) => console.log(row));
I encounter an error:
TypeError: rows is not iterable.
However, if I append a string instead of a number, for example:
setRows([...rows, 'a'])
I have a React component where I'm using the useState hook to manage an array. Initially, my state is defined like this:
const [rows, setRows] = useState([1]);
When I try to append a number to the array using a button click:
setRows([...rows, 1])
and iterate through the rows
:
rows.map((row) => console.log(row));
I encounter an error:
TypeError: rows is not iterable.
However, if I append a string instead of a number, for example:
setRows([...rows, 'a'])
1 Answer
Reset to default 0In react ,when using usestate
hook for managing arrays, you typically want to update the sate in an immutable way. This means you should create a new array that includes the existing elements along with the new element you want to add. The issue you are having with adding a number to usestate
array making if 'non-iterable'.
Correct Way
When you want to add an element to an array in state, you should use spread operator(...)
.
Example
const [myArray,setMyArray] = useState([]);
//Adding a number
const addNumber = () => {
setMyArray(prevArray=>[...prevArray,number]);
}
console.log(typeof rows);'
console.log(Array.isArray(rows));
console.log(rows);
after definition and right before map. If it have changed, it means you are modifying it somewhere else somehow. Strings are iterables (it iterates through the characters), numbers are not. – Flash Thunder Commented Nov 20, 2024 at 6:31