I'm trying to build a simple app that fetches data from an API and shows them. I have a scenario in which I have to fetch the IDs of some items, and then for every ID make an API call to get the details. I want to set the array of fetched details as a state, and I can actually do it, but the view does not update and I don't understand why... I guess I'm doing a mess with asynchronous calls, as always...
updateSearchResults()
is a state setter passed as a prop from the upper level component, and the holder of the state is that same upper level component.
async function handleSubmit(event) {
event.preventDefault();
if(name) {
let res = await axios.get(`https://www.foo.bar/search`);
if(res.data.items !== null) {
const filteredItems = filterItems(res.data.items);
updateSearchResults(filteredItems); //this works as expected
}
} else {
let res = await axios.get(`https://www.foo.bar/anothersearch`);
if(res.data.items !== null) {
let items= [];
res.data.items.forEach(async item => {
const resDetails = await axios.get(`https://www.foo.bar/getdetails`);
items.push(resDetails.data.items[0]);
})
console.log(items); //this prints the expected result
updateSearchResults(items); //this updates the state but not the view
}
}
}