4

Im working on a project that displays a random food title and the image of that food. Im having trouble figuring out why the data displays on the page only once and once I refresh the page, it gives an error of "Uncaught TypeError: recipeList.recipes is undefined".

This is my home.js

import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";

const URL = `https://api.spoonacular.com/recipes/random?apiKey=${APIKey}&number=1`;

console.log(URL);

function Home() {
  const [food, setFood] = useState({});

  useEffect(() => {
    axios
      .get(URL)
      .then(function (response) {
        setFood(response.data);
      })
      .catch(function (error) {
        console.warn(error);
      });
  }, []);

  return (
    <main>
      <Recipe recipeList={food} />
    </main>
  );
}

export default Home;

and this is my Recipe.js component

import React from "react";

function Recipe({ recipeList }) {
  return (
    <div className="recipeCard">
      <h1>{recipeList.recipes[0].title}</h1>
      <img src={recipeList.recipes[0].image} alt="Food" />
    </div>
  );
}

export default Recipe;

3 Answers 3

2

you should verify if you data food is not empty or null, here an example:

<main>
     {food &&
      <Recipe recipeList={food} />}
</main>

first at all you need to load the datas in useeffect

useEffect(() => {
const loadData=()=>{
    axios
      .get(URL)
      .then(function (response) {
        setFood(response.data);
      })
      .catch(function (error) {
        console.warn(error);
      });
}
if(!food){ // just for dont load empty data -->setFood(response.data)
loadData()
}
  }, []);

you are loading empty data when you reload the page

2
  • it does always returns a random food that has data (I checked in the console.log(URL) but it just only shows when I first save my code. when I refresh it, it shows an error of "recipeList.recipes is undefined".
    – mw3981
    Commented Oct 23, 2021 at 2:51
  • I have updated my code to look like yours but the image and title still doesn't show up ?
    – mw3981
    Commented Oct 23, 2021 at 17:00
0

rn3w beat me to it. The error message is indicating that recipeList.recipes does not exist, which is correct because when the Recipe component is initialized recipeList (food from the Home component) is set to {}.

the data displays on the page only once and once I refresh the page, it gives an error...

The mystery to me is why the data displays on the page the first time! Seems like it should start out with the error message.

0

You're using a dependency array which is [] empty, Hence only the first call is working.

Not the answer you're looking for? Browse other questions tagged or ask your own question.