The ingredients data is not showing on the page after I call the setState method to the this.state.ingredients
I have tried to change the different parameters in my code such as res.data.recipes, etc
import React from 'react';
import Form from './RecipeForm';
import axios from 'axios';
const API_KEY = 'f562842f0ff6b2d4fd24b9601aeb5e1b';
class HomeScreen extends React.Component {
state = {
ingredients: []
};
componentDidMount() {
axios
.get(
'https://www.food2fork.com/api/search?key=f562842f0ff6b2d4fd24b9601aeb5e1b&q=shredded%20chicken'
)
.then(res => {
console.log(res);
this.setState({
ingredients: res.data
});
});
}
render() {
const recipeList = this.state.ingredients.length ? (
this.state.ingredients.map(ingredient => {
return (
<div key={ingredient.recipe_id}>
<p>{ingredient}</p>
</div>
);
})
) : (
<div>There are no ingredients here</div>
);
return (
<div style={{ padding: 50 }}>
<Form />
<div>{recipeList}</div>
</div>
);
}
}
export default HomeScreen;
There is no output to the page where I map out the data
Here is the console.log I have
config: {url: "https://www.food2fork.com/api/search?key=bfb76b78b11e7308cc3c027865a508dd&q=shredded%20chicken", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data:
count: 30
recipes: Array(30)
0: {publisher: "Closet Cooking", f2f_url: "http://food2fork.com/view/35171", title: "Buffalo Chicken Grilled Cheese Sandwich", source_url: "http://www.closetcooking.com/2011/08/buffalo-chicken-grilled-cheese-sandwich.html", recipe_id: "35171", …}
1: {publisher: "All Recipes", f2f_url: "http://food2fork.com/view/29159", title: "Slow Cooker Chicken Tortilla Soup", source_url: "http://allrecipes.com/Recipe/Slow-Cooker-Chicken-Tortilla-Soup/Detail.aspx", recipe_id: "29159", …}
2: {publisher: "My Baking Addiction", f2f_url: "http://food2fork.com/view/e7fdb2", title: "Mac and Cheese with Roasted Chicken, Goat Cheese, and Rosemary", source_url: "http://www.mybakingaddiction.com/mac-and-cheese-roasted-chicken-and-goat-cheese/", recipe_id: "e7fdb2", …}```
In your componentDidMount
, you need to set ingredients
to res.data.receipes
instead of res.data
. res.data
is only the server's response payload. If you want to access some of the data inside, it you have to index into the response object further. However, this isn't always good because sometimes (if an error occurs) recipes
may not be there. In that case, you should have a catch
block (like in the Axios docs).
this.setState({
ingredients: res.data.receipes
});