Stephanie Parker
Stephanie Parker

Reputation: 401

Trying to destructure a value from an object returns an error

I'm trying to fetch a name property from an object using destructuring but the error returning says 'cannot read property name of undefined.

    // Get genres for given movie
    getGenres = (genreIds, genres) => {
        return genreIds.map(genreId => {
            const filteredGenres = genres.filter(genre => genre.id === genreId);
            const { name } = filteredGenres[0];
            return name;
        })
    };

If I console log filteredGenres[0] I do get a valid object back with a name and id, I've also checked this with typeof to ensure. The result is: {id: 14, name: "Fantasy"}

If i try to console log filteredGenres[0].name I also get the same cannot read property name of undefined error.

I'm not entirely sure what I'm doing wrong? Any help is really greatly appreciated! :)

I've created a stackblitz as requested. File in question is NowPlaying.js

https://stackblitz.com/edit/react-ow3x3u

Upvotes: 1

Views: 181

Answers (1)

Pierre C.
Pierre C.

Reputation: 1430

As per your Stackblitz sample, the state property genres is initialized as an empty array.

This means that when you pass this as a prop to NowPlaying, filterGenres will also be an empty array and thus the error you get.

This happens only before the genres are fetched. After genres is fetch and the state is updated, the state is updated and everything looks fine.

You have to account for the genres array being empty.

Upvotes: 1

Related Questions