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;
CodePudding user response:
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
CodePudding user response:
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.