0

I fetch an api on componentDIdMount() then store the json to a state then I pass that state as a prop, I have no problem showing the data except on arrays.

<Component details={this.state.details} />

json:

    {
    "adult": false,
    "backdrop_path": "/qonBhlm0UjuKX2sH7e73pnG0454.jpg",
    "belongs_to_collection": null,
    "budget": 90000000,
    "genres": [
    {
    "id": 28,
    "name": "Action"
    },
    {
    "id": 878,
    "name": "Science Fiction"
    },
    {
    "id": 35,
    "name": "Comedy"
    },
    {
    "id": 10751,
    "name": "Family"
    }
    ]
    }

then I try to map the genres:

<div className={style.genre}>
   {details.genres.map(g => (
      <span key={g.id}>{g.name}</span>
   ))}
</div>

But then I get Cannot read property 'map' of undefined, I don't know why this is happening because I'm able to do details.budget

1
  • Can you share more info, like where are you calling your API, how are you storing details? As the code you have shared is working okay on console so there might be problem perhaps with the way of implementation like using details way before it has been assigned value. Commented Feb 24, 2020 at 5:55

1 Answer 1

1

It's trying to read data before you get the result from api. so write the map function as

    {details&&details.genres&&details.genres.map(g => (
      <span key={g.id}>{g.name}</span>
   ))}

In react Initially when component is mounted, render() function is called and then componenentDidMount() is called in which you fetch data. So Initially details is empty. So you need to write the condition.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thank you for your answer, I did something similar before which is /*details.genres !== null &&*/ but I still go the same error so what does the condition /*details &&*/ mean?
That might be because details.genres is undefined. And undefined!==null returns true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.