DEV Community

sanderdebr
sanderdebr

Posted on

1

Chaining async await API calls in Redux

Chaining async await API calls in Redux

While learning Redux I encountered several problems from which I will share the solutions to you in this article.

Let’s say you want to fetch data from the Pokémon API https://pokeapi.co/ using Redux.

Example: https://master.d1or1a1srkom3l.amplifyapp.com/
Github repo: https://github.com/sanderdebr/pokedex

We will handle these async API calls outside of our main reducers of actions, instead we will use Redux Saga.

Inside our saga we have a watcherSaga and workerSaga, everytime the action DATA_REQUESTED gets called it will fire our workerSaga which fetches the return of our API call.

Our fetch function fetchAll() is an async function that retrieves a list of pokemon names. Based on this list we retrieve details for every pokemon by nesting API calls within fetchAll(). The function returns aPromise.all object that contains nested fetches described in another function called fetchPokemon().

Besides that I’ve included a timer that returns the milliseconds it took to fetch the data.

import { takeEvery, call, put } from 'redux-saga/effects';
import actionTypes from '../constants/action-types';
export default function* watcherSaga() {
yield takeEvery(actionTypes.DATA_REQUESTED, workerSaga);
};
function* workerSaga() {
try {
const payload = yield call(fetchAll);
yield put({ type: actionTypes.DATA_LOADED, payload })
} catch (e) {
yield put({ type: actionTypes.API_ERROR, payload: e })
}
};
// Fetch a list of pokemon names
// Chaining promises and checking Promise.all
async function fetchAll() {
let pokemons = [];
let start = performance.now();
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`);
const json = await response.json();
const arr = json.results;
return Promise.all(arr.map(async pokemon => {
const result = await fetchPokemon(pokemon);
pokemons.push(result);
})).then(() => {
let end = performance.now();
let timer = parseInt(end - start);
return {pokemons, timer};
});
} catch (e) {
throw new Error(`fetching list of pokemons went wrong`);
};
};
// Get pokemon details for each pokemon
async function fetchPokemon(pokemon) {
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon.name}`);
return await response.json();
} catch (e) {
throw new Error(`fetching ${pokemon.name}'s details went wrong`);
}
};
view raw fetch-saga.js hosted with ❤ by GitHub

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay