0

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
            }
        }
    }
Essay97
  • 648
  • 1
  • 9
  • 24

2 Answers2

0

You can modify your code to something like this:

 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= [];
            for await (const item of res.data.items) {
                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
        }
    }
}
Yatin Gaikwad
  • 1,140
  • 1
  • 13
  • 23
0
...
const items= await Promise.all(res.data.items.map(async item =>  {
  const resDetails = await axios.get(`https://www.foo.bar/getdetails`);
  return resDetails.data.items[0];
}));
console.log(items); //this prints the expected result
updateSearchResults(items);
Dmitriy Mozgovoy
  • 1,419
  • 2
  • 8
  • 7