0

I am new to React JS. In my application I am facing a situation where I need to call an API multiple times with different url, like apiurl.com/abc, apiurl.com/xyz. These abc and xyz are stored in an array. Hence I wanted to use .map() to change the url to make multiple api calls. But in .map() async await wont work, so looking for some solutions if any. I have gone through few possible solution like with promises, but could not implement.

Here is my code:

export const someAction = () => async (dispatch, param) => {
let myArray = ["abc", "xyz"];
let id= "";
param1 = "someauthcode";
myArray.map((x) => {
    id = x;
    const myResponse = await loaders.myResponseApi(param1, id); *//This does not work as await should be in async call*
});
dispatch({ type: types.ARRAY_API, payload: myResponse });

}

So the idea is to make 2 api calls with apiurl.com/abc, apiurl.com/xyz. I have constructed the url (apiurl.com) in an different file.

Thanks in advance.

Saswata Sundar
  • 586
  • 1
  • 4
  • 15

2 Answers2

3

Turn your array into an array of promises and then use Promise.all

export const someAction = () => async(dispatch) => {


   try {
     const payload = await Promise.all(myArray.map(id => loaders.myResponseApi(param1,id)));
     dispatch({type:types.ARRAY_API,payload});
   } catch(err) {
     // an error occurred in at least one of the promises
   }

}
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
2

Instead of using .map() you can use a traditional for or while loop:

export const someAction = () => async (dispatch, param) => {
    let myArray = ["abc", "xyz"];
    let id= "";
    param1 = "someauthcode";
    let i = 0;
    while (i < myArray.length) {
        id = myArray[i];
        const myResponse = await loaders.myResponseApi(param1, id);
        // handle response here...
        i++;
    }
}
JusMalcolm
  • 1,431
  • 12
  • 10