by Max Caluva
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.
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.
We need to install it through npm:
npm install redux-thunk
Add –save if you’re not using npm@5
We suppose that you have a redux implementation in your app, so let’s start writing some code directly.
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.
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:
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):
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:
Feel free to use it as boilerplate or just for example purposes.