The Setup
Have you ever worked with applications where you use redux for state management? I am sure you have. It's beautiful how the framework lets us use the one way state flow by dispatching actions, making use of pure functions and immutability to provide a nearly perfect state management option for small/medium apps.
But there is an issue I have with redux: the boilerplate that comes associated with it.
The Issue
Although redux is not opinionated, there is generally a standard way of doing stuff: write action creators, use functions like 'mapStateToProps', 'mapDispatchToProps', use the 'connect' function, use thunk for async actions etc.
One of those "standards" is the way in which one performs a simple request, success/failure operation on an API.
Here's the drill:
- Create a 'REQUEST' action and dispatch it.
- Make the network request.
- On success, dispatch the 'SUCCESS' action with the payload.
- On failure, dispatch the 'FAILURE' action with the error.
This is so common that react official documentation has an entire article on how to minimize boilerplate for this pattern:
https://redux.js.org/recipes/reducing-boilerplate
The actual Issue
But what if your problem statement does not fit into the straightjacket of this pattern mentioned above and you are unable to use any of the solutions mentioned in the link above. Same was the case with my problem statement and I thought to myself how I can still reduce my boilerplate.
Then, I Stumbled upon my constants.js file that held my actions. It looked something like this:
and whenever I wanted to import actions, I did this:
Or worse still, in some cases the constants were imported like so:
A better way
Here's how the constants file can be made smaller, concise and easier to read.
First, write a util function and call it something like:
Then, the constants.js file can look something like this:
And the constants can then be used in this manner:
So, in this way, we can minimize at least the constants boilerplate that causes files to bloat up and makes the code less understandable.
Top comments (0)