Petra Jakubcova
Petra Jakubcova

Reputation: 105

Error while rendering an array.map() in React

I'm super new to React and this might be a dumb question but I'm getting an error saying: Uncaught TypeError: Cannot read property 'map' of undefined when I'm trying to display the ingredients for each recipe. I'm not sure if I can use an array.map inside of the return statement, or where else should I include it, if it is a part of my component? I just want to go through the ingredients and display them . Thanks for any help![Screenshot of my console]1

   import React, { Component } from "react";

    class Recipe extends Component {
        state = {
            activeRecipe: []
        }
        componentDidMount = async() => {
            const title = this.props.location.state.recipe;
            const req = await fetch
            (`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);

            const res = await req.json();
            this.setState({ activeRecipe: res.hits[0].recipe});
            console.log(this.state.activeRecipe);
            }
            render() {
                const recipe = this.state.activeRecipe;
                return (
                   <div className="container">
                       <div className="active-recipe">
                           <h3 className="active-recipe">{recipe.label}</h3>
                           <div className="container">
                           {recipe.ingredients.map(ingredient => {
                            return (
                                <p>{ingredient.text}</p>
                            );
                           })}
                           </div>
                       </div>
                   </div>
                );
            }
    }

    export default Recipe;

Upvotes: 0

Views: 82

Answers (1)

Matt Oestreich
Matt Oestreich

Reputation: 8528

This is because your component is rendered/mounted before the async call can finish..

If you change:

recipe.ingredients.map(ingredient => {

to this:

recipe.ingredients && recipe.ingredients.map(ingredient => {

It should work as you are wanting.

This is because map does not get called unless ingredients exist.

Upvotes: 1

Related Questions