The Fetch API and asynchronous Redux state

Charles Stover
7 min readOct 9, 2018

If you are building a complex React application, you are likely using a back end service and an API. If you are managing state in React, you likely are using redux. Both are great choices that I would highly recommend for your React application’s architecture. However, redux’s out-of-the-box synchronous state manipulation is not particularly compatible with asynchronous server responses, leaving many developers scratching their heads. There are a lot of states involved in an asynchronous call, but isn’t an API call just a single action?

I would like to walk you through the standardized states involved in an asynchronous API call and their relationship to the redux store.

By the end of this article, you should understand how to write an asynchronous redux action that handles each state of an API call. Each API call has the same states and logic behind when those states are triggered, so in order to prevent copy-pasting the same boilerplate for each asynchronous redux action, I will also offer an open-source package that I’ve used almost religiously that will handle the action creation for you.

Prerequisites 📍

To enable asynchronous actions on your redux store, you will want to apply the redux-thunk middleware.

For API calls, I will be using the standardized fetch API. If your target browser does not support the fetch API, I would recommend a fetch polyfill. I also recommend using an AbortController polyfill if you want to be able to abort your API calls, but not if you do not desire this feature. If you prefer an alternative to the fetch API, such as axios or XMLHttpRequests, they are absolutely capable of handling asynchronous redux state management, but my code examples will be based on the fetch API.

What is an asynchronous action? 🐌

The first step is understanding what you are creating — unlike previous action creators that returned an action object that was immediately sent to the reducers, an asynchronous action is not an object but a function that is immediately invoked. That function accepts two parameters, each of which is a function. The first is the dispatch function, used to dispatch an action; the second is a getState function, used to get the current…

--

--