RoyBarOn
RoyBarOn

Reputation: 987

How to call Api multiple times with different parameters and then store the responses?

I'm using react with redux for a small application that shows weather forecasts and the user can save a city forecast to a favorites list. The city forecast that stored is the city's id, so the favorites array looks like that :

favoriteCities : ['12211', '43434', '43435'] // each id represent a city unique id.

The action that's calling the api for single city - looks like this:

export const getCurrentForecast = (cityCode) => {

    return async dispatch => {
        fetch(`http://dataservice.accuweather.com/forecasts/v1/daily/5day/${cityCode}?apikey=${apiKey}&metric=true`)
            .then(function (response) {

                return response.json();
            })
            .then(function (data) {
                return dispatch({
                    type: "GET_CURRENT_FORECAST",
                    payload: data
                });
            });
    };
};

How can i get all the cities forecasts from the same request but with different parameter? (cityname)

Here is what i had in mind (it's just a rough sketch)

let citiesForecasts = [];
for(let i=0; i < favoriteCities.length; i++){
   // iterate over the favorite cities codes
   let currentCityCode = favoriteCities[i];
   citiesForecasts.push(getCurrentForecast(currentCityCode )) // push the result object
}

Disclaimer: although it's seems like a duplicated post - it's not - i've looked in many posts and didn't found a sufficient answer.

Upvotes: 0

Views: 2156

Answers (1)

user11910739
user11910739

Reputation:

You can simply achieved it by using Promise.all. Check below code.

let citiesForecasts = [];
favoriteCities.map(city => citiesForecasts.push(getCurrentForecast(city)));

Promise.all(citiesForecasts).then((results) => {
   // results will comes in type of array
}).catch((err) => {
    console.log(err);
});

In alternative way you can also use axios library and use axios.all method to call multiple request.

Hope this will work for you!

Upvotes: 1

Related Questions