-2

I have an array of id's and I am trying to iterate over that array to make an api call for each id present. However my api call doesnt seem to be going through can anyone provide some insight?

the array of id's looks something like this: ["provider-e44f1ccd-839c-413b-9559-0d2b359ee541", "provider-1cd9c1fe-de26-4b44-a1b9-03e6fc103ac4", "provider-1cd9c1fe-de26-4b44-a1b9-03e6fc103ac4", "system", "system", "provider-1cd9c1fe-de26-4b44-a1b9-03e6fc103ac4"]

my function to make the call looks like this :

useEffect(() => {
    const loadProvider = async () => {
        
      if(entries.length > 0){
        const providerID = entries.map((entry => entry.createdBy))
        console.log(providerID)
        try{
            const results = await api.Providers.get(providerID[+i])
            console.log(results, "12345678987654321")
    }catch(err){}
      }
    };

   loadProvider();
  }, [entries]);

I am able to get inside the try statement but only one call is returned when i console results

I also tried using to map over entries inside the try statement but I got a syntax error for my await result variable.

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
CourtneyJ
  • 458
  • 6
  • 19

2 Answers2

1

providerID is an array. You would do well to rename it to something that reflects that. Like providerIDs, for example.

providerID[+i] is a syntax error.

If you want to make an API request for each id, you have to somehow iterate your providerIDs array. You can do that using a forEach:

useEffect(() => {
  const loadProvider = () => {
    const providerIDs = entries.map((entry) => entry.createdBy);
    providerIDs.forEach(async (id) => {
      try {
        const result = await api.Providers.get(id);
        console.log(result);
      } catch (error) {
        console.log(error);
      }
    })
  };

  loadProvider();
}, [entries]);
Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
  • I understand your solution but Ive tried it and it always gives me a syntax error this is the same reason i left the map outside of the try statement. The error says that `await is a reserved word` – CourtneyJ Feb 26 '21 at 21:09
  • Ah, it looks like that in order to use `await`, the function directly enclosing it needs to be `async`. You can read more about it [here](https://stackoverflow.com/questions/42299594/await-is-a-reserved-word-error-inside-async-function). – Janez Kuhar Feb 26 '21 at 21:15
0

You can use Promise.all and .map

let results = await Promise.all(entries.map(async (entry) => {
    try {
      const result = await api.Providers.get(entry.createdBy)

      return result;
    } catch(error) {
      //handle errors
    }
  }));
Nonik
  • 645
  • 4
  • 11