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
JavaScript
x
32
32
1
import React, { useEffect, useState } from "react";
2
import axios from "axios";
3
import Recipe from "../components/Recipes";
4
5
const URL = `https://api.spoonacular.com/recipes/random?apiKey=${APIKey}&number=1`;
6
7
console.log(URL);
8
9
function Home() {
10
const [food, setFood] = useState({});
11
12
useEffect(() => {
13
axios
14
.get(URL)
15
.then(function (response) {
16
setFood(response.data);
17
})
18
.catch(function (error) {
19
console.warn(error);
20
});
21
}, []);
22
23
return (
24
<main>
25
<Recipe recipeList={food} />
26
</main>
27
);
28
}
29
30
export default Home;
31
32
and this is my Recipe.js component
JavaScript
1
14
14
1
import React from "react";
2
3
function Recipe({ recipeList }) {
4
return (
5
<div className="recipeCard">
6
<h1>{recipeList.recipes[0].title}</h1>
7
<img src={recipeList.recipes[0].image} alt="Food" />
8
</div>
9
);
10
}
11
12
export default Recipe;
13
14
Advertisement
Answer
you should verify if you data food
is not empty or null, here an example:
JavaScript
1
5
1
<main>
2
{food &&
3
<Recipe recipeList={food} />}
4
</main>
5
first at all you need to load the datas in useeffect
JavaScript
1
16
16
1
useEffect(() => {
2
const loadData=()=>{
3
axios
4
.get(URL)
5
.then(function (response) {
6
setFood(response.data);
7
})
8
.catch(function (error) {
9
console.warn(error);
10
});
11
}
12
if(!food){ // just for dont load empty data -->setFood(response.data)
13
loadData()
14
}
15
}, []);
16
you are loading empty data when you reload the page