I am doing a fetch and trying to add the contents of a new array to an existing array that is held in state (in a useContext and imported into my component)
const [songNames, setSongNames] = useState([])
.then((data) => {
let newSongsToAdd = []
data.data.forEach((song) => {
... some logic ...
newSongsToAdd.push(song)
}
setSongNames(prevArray => [...prevArray, ...newSongNameArray])
}
I get the error "Uncaught TypeError: prevArray is not iterable". I think I’ve tried every which way, but I can’t seem to figure out why the songNames array I have in state is not iterable.
The function otherwise works (I can replace the state, just not spread the new data into it).
Any ideas? Full error below, thanks!
Uncaught TypeError: prevArray is not iterable
at HomePage.js:145:1
at basicStateReducer (react-dom.development.js:16540:1)
at updateReducer (react-dom.development.js:16664:1)
at updateState (react-dom.development.js:17004:1)
at Object.useState (react-dom.development.js:17915:1)
at useState (react.development.js:1622:1)
at Provider (Context.js:19:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
>Solution :
To fix the error "Uncaught TypeError: prevArray is not iterable", you can make sure that the songNames array is always initialized with an empty array, even if the initial value is null or undefined. This will ensure that the songNames array is always iterable, and you will be able to spread its values into a new array.
Here is an example of how you can fix the error by initializing the songNames array with an empty array:
const [songNames, setSongNames] = useState([])
// ...
.then((data) => {
let newSongsToAdd = []
data.data.forEach((song) => {
// ... some logic ...
newSongsToAdd.push(song)
}
setSongNames(prevArray => [...(prevArray || []), ...newSongNameArray])
})
In the code above, the prevArray || [] expression ensures that the prevArray is always an array, even if it’s null or undefined. This allows you to spread its values into a new array, and avoid the "Uncaught TypeError: prevArray is not iterable" error.
I hope this helps!