Async actions handling with redux-thunk

Using redux-thunk to work with asynchronicity

One of the common issues I found when working with Redux is to handle async data correctly, mostly when you want to do in-between steps, e.g. calling a service or transform the data in any way. Here is a short tutorial with simple steps to work with async calls in Redux.

ENTER THE THUNK

First off, what is a thunk?

A thunk is a function that wraps an expression to delay its evaluation.

Now, what does redux-thunk do?

From the creator Dan Abramov’s words:

It allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.

Redux Async Actions infography

HOW DO WE USE REDUX-THUNK?

We need to install it through npm:

npm install redux-thunk

Add –save if you’re not using [email protected]

We suppose that you have a redux implementation in your app, so let’s start writing some code directly.

First let’s include redux-thunk into our application, in the store, and add it to the middlewares of it:

THE ASYNC ACTION CREATORS

Now we are able to start writing our thunks, in the file where we define our actions, I decided to add a new export, remember, this function needs to return a new function that accepts dispatch as a parameter:

I’m going to create an Action Creator that fetches a list of people from a mocked API call, feel free to use your own implementation.

THE REDUCER

As we can see, we end up firing an action with the type FETCH_PEOPLE_HAS_FINISHED, we need to handle that on our reducer:

We also need another reducer for the loading:

SHOWING ASYNC DATA IN THE VIEW

Now we can easily use this data on our view to either show a loader while the data is fetching, or something else (Please check at the end of the post for a working example):

THE END: A REDUX-THUNK WORKING EXAMPLE

And that’s it, we now know how to create async actions with redux-thunk!

Also, here is a sample repository with redux-thunk already implemented:

https://github.com/nanlabs/redux-thunk-demo

Feel free to use it as boilerplate or just for example purposes.

Need to develop an app?