My application fetches data from two api endpoints at the same time and combines the data into a single, nested json object like this:
{
"Shop1": [
{
"product_name": "Shop 1 Wine",
"product_price": "4.99"
},
{
"product_name": "Shop1 Wine 2",
"product_price": "4.49"
}
],
"Shop2": [
{
"product_name": "Shop 2 Wine",
"product_price": "4.99"
},
{
"product_name": "Shop 2 Wine 2",
"product_price": "4.49"
}
]
}
This is how the data is being fetched by reactjs:
function App() {
const ListLoading = withListLoading(List);
const [appState, setAppState] = useState({
loading: false,
products: null,
});
useEffect(() => {
setAppState({ loading: true });
const baseUrl = "http://localhost:8080/"
const searchItem = "wine"
const shops = [
"Shop1",
"Shop2"
];
let urls = [];
const allUrls = shops.map((shop) => {
let url = baseUrl + shop + "/" + searchItem;
urls.push(url)
});
function fetchData() {
const allRequests = urls.map(url =>
fetch(url).then(response => response.json())
);
return Promise.all(allRequests);
};
fetchData().then(arrayOfResponses =>
setAppState({loading: false, products: arrayOfResponses})
);
}, [setAppState]);
return (
<div className='App'>
<div className='container'>
<h1>Products</h1>
</div>
<div className='repo-container'>
<ListLoading isLoading={appState.loading} products={appState.products} />
</div>
<footer>
</footer>
</div>
);
}
export default App;
Then in the actual page I have this:
import React from 'react';
const List = (props) => {
const { products } = props;
if (!products || products.length === 0) return <p>No products, sorry</p>;
return (
<ul>
<h1>{products}</h1>
<h2 className='list-head'>products</h2>
{products.map((product) => {
return (
<li className='list'>
<span className='{product.shop_name}'>{product.product_name} </span>
<span className='repo-description'>{product.product_price}</span>
</li>
);
})}
</ul>
);
};
export default List;
I want to be able to run through each element in the json object and in place of product.shop_name place top level value(like shop1 or shop2) and then in span blocks the values relevant to a given shop(like product_name and product_price).
Currently I'm getting the following error:
Error: Objects are not valid as a React child (found: object with keys {Shop1}). If you meant to render a collection of children, use an array instead..
How can I get react to loop through each level 1 value and then do the same for level 2 values and display them in html?
arrayOfResponseslooks like.arrayOfResponsesis the json object as shown at the top of my question. I can access the data for shop1 by accessingarrayOfResponses[0]