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?