Dariusz Legizynski
Dariusz Legizynski

Reputation: 386

How in useState iterate over an array

I have the following problem with a (hopefully) basic function of useState which I do not get yet. I wanna get a todo list with all the previously written tasks. I try to solve it in two ways:

First approach:

const [ favoritedList, setFavoritedList ] = useState([]);

const handleFavoritedVideo = (favoritedElement) => {
    setFavoritedList((previousFavorited) => {
        return [ favoritedElement, ...previousFavorited ];
    });
};

everything is working fine.

But when I try to do something like this:

const [ favoritedList, setFavoritedList ] = useState({favorited:[]});

const handleFavoritedVideo = (favoritedElement) => {
    setFavoritedList((previousFavorited) => {
        return [ favoritedElement, ...previousFavorited ];
    });
};

I get the following error:

TypeError: previousFavorited is not iterable

Why is this and how to fix it?

Upvotes: 2

Views: 1742

Answers (2)

Anis R.
Anis R.

Reputation: 6902

In the second version, you are setting favoritedList to an object of the form {favorited: []}.

So in the function, your previousFavorited is not the list, but an object containing the list, which you should access using previousFavorited.favorited.

The affected code becomes something like:

return {favorited: [ favoritedElement, ...previousFavorited.favorited ]};

(Edit: there was a slight mistake in the code I wrote, corrected as per @mikeboharsik 's answer)

Upvotes: 1

mikeboharsik
mikeboharsik

Reputation: 110

useState({favorited:[]}) is initializing favoritedList to an object.

previousFavorited in setFavoritedList is whatever the current value of favoritedList is, which is an object. Therefore you are trying to use ... on an object, which is not iterable like an array is and is invalid.

My recommendation would be to use useState([]) to initialize favoritedList to a normal array, and then you can simply treat it as an array.

If you really must use an object for favoritedList, the solution would be to return an object to keep the object structure consistent:

return { favorited: [favoritedElement, ...previousFavorited.favorited] }

Upvotes: 2

Related Questions