'I send data as props to components. But, only the last component showing data
I wanted to build a food web app. I wanted to fetch data from api and send to different components. When components will be clicked they will show data according to the props send to them.
But, here the problem is only the last component is showing data. others are not.
Image1(Home.js)
Image2(Home.js-remaining)
Image3(Breakfast component)
Image4(Lunch Component)
Image5(Dinner component)
Image6(Output1)
Image7(Output2)
Image8(Output3)

Solution 1:[1]
Ok so a few things:
- Post your actual code, not pictures of code
- The
.mapfunction if for building a new array, it's not really meant for looping over an array, use something like.forEachfor that - Each
.mapiteration you're callingsetBreakfast(or one of the other ones) and overwriting the previous state value. You want to build an array and set the state to that array - As a general rule don't update React state in a loop, it's inefficient and can causes issues. Run a loop to build a value/data structure, then set the state to that
What you want to do it something like this:
.then(
setBreakfast(data.map(food => food.breakfast));
setLunch(data.map(food => food.lunch));
setDinner(data.map(food => food.dinner));
);
That way you're setting the state value to the return value of .map, which is an array containing all the corresponding meal values for that meal type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jayce444 |
