Write and test Redux async action-creators faster
This writeup assumes you are fluent with the redux library. Most people use redux-thunk to create asynchronous action creators in React. But, I’m glad to present redux-promise-middleware as an alternative to redux-thunk. I’ll also dive into simple tests for the redux-promise-middleware async action-creators.
Why Redux-promise-middleware ?
The main reason for choosing redux-promise-middleware is nothing more than a perpetual belief;
“Laziness is a virtue, and there is a constant desire to write as little code as possible.”
I have REST API for a BucketList application already built, which the redux async action creators will consume.
Below is a comparison of async action creators with redux-thunk and redux-promise-middleware.
Redux Thunk
Redux Promise Middleware
Well, you might be pondering … what just happened? Do the previous snippets of code all achieve the same result as async action creators?
Yes, they do !!
Comparing the above snippets of code shows that code written with redux-promise-middleware is more compact and readable. It indeed aligns with the overall belief that laziness is a virtue.
How redux-promise-middleware works?
The promise middleware listens if the payload returns and a promise or not. If the promise is resolved, the middleware appends_PENDING, _FULFILLED or _REJECTED
to the dispatched action type.
For instance getBucketLists async action creator will dispatch GET_BUCKETLISTS_PENDING
before the promise is resolved and either GET_BUCKETLISTS_FULFILLED or GET_BUCKETLISTS_REJECTED
depending on whether the promise is successful or rejected.
Now, its time to roll up the sleeves and get writing some code.
Getting Started with redux-promise-middleware
First, we install redux-promise-middleware
, to enable us handle the async action creators gracefully. As a bonus, install redux-logger
to help us view the dispatched actions by our async actions creators.
npm install --save redux-promise-middleware redux-logger
Store Configuration
We then configure the redux-store as follows, applying both the promise and logger middleware.
As mentioned, I have a Bucketlist REST-API already built, and the react application will consume it using the axios
library. Some routes require token authentication. The token is stored in a redux store.
npm install --save axios
I created an axios
instance as below in the interest of upholding the DRY principles.
Testing
“All Code is broken without tests”
Tests are great practice and I strongly recommend them in every software project. Below are the necessary libraries I used for testing
Jest — Main testing library
Moxios — To mock axios
Redux-mock-store — To mock the redux store
npm install --save-dev moxios redux-mock-store
The test below asserts that the proper actions are dispatched when the getBucketLists
async action creator is called.
Connect with me via Twitter or LinkedIn
Till next time, never stop learning.
Aluta continua