0

I am continuously running into this error with my first non-trivial React project. The error specifically is "TypeError: Cannot read property 'map' of undefined." The reason this error is happening is because React seems to load every component twice while I'm testing it.

Here's what I mean. I am trying to create a list of song names from a JSON I am receiving from the Spotify API. Each time the app loads I need to authenticate with Spotify before I can receive the data. I believe this is causing the undefined error as React is loading the component with the map function before there is data to map over.

import React from 'react';

function List(props) {

    const userData = props.userData;
    const favorites = Object.values(userData)[0]; // turns JSON object into usable array

    // console.log(favorites)
    // try {
    //     favorites.map( (item) => console.log(item.name));
    // } catch {
    //     console.log("No favorites");
    // }
    
    return (
        <div>
            <p>Your favorite songs are:</p>
            <ul>
                {favorites.map( (item) => (<li key={item.id}>{item.name}</li>))}
            </ul>
        </div>
    );
}

export default List;

If I uncomment out the try/catch statement and scrap the return statement, I get a console output that looks like this.

So my question is how/why is this happening? What is the best way to map over data you don't have yet?

tinkoh
  • 366
  • 4
  • 10
  • You can either a) make sure `favorites` is always an array by setting it to `[]` initially, or b) use conditional rendering to skip it `{favorites && favorites.map && favorites.map(...)}` (also, please try googling `react cannot read map of undefined` next time, which will yield dozens of existing answers) –  Mar 23 '21 at 15:48
  • you can add a condition in your return like `return({favorites &&
    ......
    });`
    – antoineso Mar 23 '21 at 15:48
  • 1
    Duplicate [Cannot read property 'map' of undefined](https://stackoverflow.com/questions/24706267/cannot-read-property-map-of-undefined) –  Mar 23 '21 at 15:50

1 Answers1

0

You have a couple of options, people normally either specify a default value or do only the processing when the value is defined, i prefer option 1, for example:

const favorites = Object.values(userData)[0] || []
marcos
  • 4,473
  • 1
  • 10
  • 24
  • Thank you! I did not know you could set default values like that, and trying to fit useState() into this didn't work out so well. – tinkoh Mar 23 '21 at 16:18