0

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;
1
  • You are rendering it before it gets downloaded, try writing the output of the this.state.activeRecipe in render, you should see undefined Commented Jan 3, 2020 at 18:00

1 Answer 1

1

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.

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

Comments

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.