Zin Myo Swe
Zin Myo Swe

Reputation: 938

Cannot read property 'map' of undefined in React and API

I am very new to react and I am trying to bring in data from a food2fork api but I am getting the error

TypeError: Cannot read property 'map' of undefined

if i undo this code, the error was none. this code is main place to occur error

  {recipes.map (recipe => {
    return <Recipe key={recipe.recipe_id} recipe={recipe}
    />;
  })}

Full Page of RecipeList.js

import React, { Component } from 'react';
import Recipe from './Recipe';
import RecipeSearch from './RecipeSearch';

export default class RecipeList extends Component {
    render() {
        const { recipes } = this.props;
        return (
            <React.Fragment>
                <RecipeSearch />
                <h1>Recipe List</h1>
                <div className="container my-5">
                    {/* title */}
                    <div className="row">
                        <div className="col-10 mx-auto col-md-6 text-center text-uppercase mb-3">
                            <h1 className="text-slanted">Recipe List</h1> 
                        </div>
                    </div>
                    {/* end title */}
                    <div className="row">
                        {recipes.map (recipe => {
                            return <Recipe key={recipe.recipe_id} recipe={recipe}
                            />;
                        })}
                    </div>
                </div>

                <Recipe />
            </React.Fragment>
        );
    }
}

In App.js:

render(){
    console.log(this.state.recipes);

    return (
      <React.Fragment>
        <RecipeList />
        <RecipeDetails />
      </React.Fragment>
    );
 }

Upvotes: 0

Views: 92

Answers (2)

Nicolas Hevia
Nicolas Hevia

Reputation: 15867

First, you are not passing any prop to RecipeList.
Change this in App.js

 return (
      <React.Fragment>
        <RecipeList recipes={this.state.recipes} />
        <RecipeDetails />
      </React.Fragment>
    );

Second, in RecipeList.js, render it only when the async function completes.
Change:

{recipes.map (recipe => {
  return <Recipe key={recipe.recipe_id} recipe={recipe}
    />;
  })}

To:

{recipes ? recipes.map (recipe => {
  return <Recipe key={recipe.recipe_id} recipe={recipe}
    />;
  }) : null
}}

Upvotes: 1

Atin Singh
Atin Singh

Reputation: 3690

I am taking it that you are keeping the recipes data in this.state.recipes in App.js

You need to pass it as props to <RecipeList component to use it as props there.

So in your App.js just do this

render(){
  console.log(this.state.recipes);

  return (
    <React.Fragment>
      <RecipeList recipes={this.state.recipes}  />
      <RecipeDetails />
    </React.Fragment>
  );
}

Upvotes: 1

Related Questions