Let's simplify redux - I

A guide to simplify the task of setting up redux

March 9, 2017 - 5 minute read -
redux. react

Hey react developers out there, if you haven’t tried your hand on redux yet you are missing out something important so just visit this Redux Link .

So assuming that you might be knowing redux by the time you reach this line, I move forward. Creating redux global state is such a pain, there are n number of files for just one part of redux state out of many and then combining them all is an unbearable pain.

Assuming everyone goes through the below mentioned irritating things , I am summing them up together below:

  1. Every reducer function which receives the state and action is nothing but either a combinations of lots of if…else statements or switch cases which again does nothing by themselves but just call the corresponding the function to return modified state.

  2. There are numerous actions where we dont return anything other than the type which again is sometimes the kebab case of the name of the function, like the one given below

     const setNetworkBusy = () => ({
       type: constants.SET_NETWORK_BUSY
     });
    
  3. Lastly, but not at least on the list, is declaring constants in which we keep writing lines, for example

       const ADD_MESSAGE = 'ADD_MESSAGE';
       const UPDATE_MESSAGE = 'UPDATE_MESSAGE';
    

So even after so many pains redux is still invincible to me, so I came up with some short tricks which simplified my work back in react apps, let’s see if this caters to your needs.

  1. getConsts():

    This method returns an object which contains all the constants as the keys of alll object and value also being the same.

    Method goes like this

       function () {
         const constants = {};
    
         for (var arg = 0; arg < arguments.length; arg++) {
           constants[arguments[arg]] = arguments[arg];
         }
    
         return constants;
       };
    

    Usage goes like this

       // old style
    
       export const ADD_MESSAGE = 'ADD_MESSAGE';
       export const DELETE_MESSAGE = 'DELETE_MESSAGE';
       export const UPDATE_MESSAGE = 'UPDATE_MESSAGE';
    
       //using getConsts()
       export default getConsts(
         'ADD_MESSAGE',
         'UPDATE_MESSAGE',
         'DELETE_MESSAGE',
       );
       /*
         output:
         {
           ADD_MESSAGE: "ADD_MESSAGE",
           UPDATE_MESSAGE: "UPDATE_MESSAGE",
           DELETE_MESSAGE: "DELETE_MESSAGE"
         }
        */
    

    Drawbacks: No independent exporting of constants


  2. getSimpleActionCreators():

    It helps in creating the action creators which returns only type and which is same as the name of action creator method but with different casing.

    method goes like this

       const captilize = function (string) {
         //Code to capitalize the first letter of give string
       };
    
       const getCamelCase = function (string) {
         //Code to conver 'GET_MESSAGES' to 'getMessages'
       };
    
       const getAction = function (constant) {
         return function () {
           return {
             type: constant
           };
         };
       };
    
       module.exports = function () {
         const methods = {};
         for (var constant = 0; constant < arguments.length; constant++) {
           methods[getCamelCase(arguments[constant])] = getAction(arguments[constant]);
         }
         return methods;
       };
    

    Usage goes like this

       //old style
    
       export const setNetworkBusy = () => ({
         type: constants.SET_NETWORK_BUSY,
       });
    
       // using getSimpleActionCreators
       export default {
         ...getSimpleActionCreators(
           constants.SET_NETWORK_BUSY,
           constatns.CLEAR_ALL_MESSAGES,
         ),
       }
    
       /*
         output
         {
           setNetworkBusy: () => ({
             type: 'SET_NETWORK_BUSY'
           }),
    
           clearAllMessages: () => ({
             type: 'CLEAR_ALL_MESSAGES'
           }),
         }
       */
    

    Drawbacks: Applicable only on particular action creator method


  3. createReducer:

    Creating reducer is the most boring work of all the times, moreover I dont like my code to get occupied by unnecessary switch cases

    So my createReducer takes in initialState and an object containing actions as key and corresponding methods to be executed as values of those keys.

    method goes like this

       function (initialState, handlers) {
         var _handlers = handlers || {};
         return function (state, action) {
           const handler = _handlers[action.type];
           var _state = state || initialState;
           if (handler) {
             return handler(_state, action);
           }
           return _state;
         };
       };
    

    Usage goes like this

       // old style
    
       /*
         ummm I dont even know the old style ;)
       */
    
       // using createReducer
    
       const initialState = {
         messages: [],
       };
    
       export default createReducer(initialState, {
         [constants.ADD_MESSAGE]: onAddMessage,
         [constants.UPDATE_MESSAGE]: onUpdateMessage,
         [constants.DELETE_MESSAGE]: onDeleteMessage,
       });
    

After all this story telling, checkout this npm module - simplify-redux, which gives all the functions wrapped in a single package.

Ps - This npm module is made by me :stuck_out_tongue: