Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Sharing Redux Actions and Reducers

Feb 20, 2020 • 8 Minute Read

Introduction

In Redux, reducers and actions are often seen in a one-to-one mapping. For most practical purposes, this holds, since we expect the outcome of a single action to make an impact at a single point in storage. But with complex applications, the requirement arises for actions and reducers to share each other. In this guide, we will explore two such practical scenarios and production-grade solutions available to them.

To provide context for the examples, a simple form submission app is created. Given below are the form UI, the actions, and the reducer for the form.

      // SimpleForm.jsx

import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { formSubmitAction } from 'formActions.js';

const SimpleForm = (props) => {
    const formData = useState({});
    const dispatch = useDispatch();
    
    return (
        <div class="myform">
            ...
            <button onClick={() => { dispatch(formSubmitAction(formData)) }}>Submit Form</button>
        </div>
    )
}

export default SimpleForm;


// formActions.js
import axios from 'axios';

export const FORM_ACTION_REQUEST = "FORM_ACTION_REQUEST";
export const FORM_ACTION_SUCCESS = "FORM_ACTION_SUCCESS";
export const FORM_ACTION_ERROR = "FORM_ACTION_ERROR";

export function formActionRequest(){
    return {
        type: FORM_ACTION_REQUEST
    }
}

export function formActionSuccess(result){
    return {
        type: FORM_ACTION_SUCCESS,
        payload: result,
        message: "Form Action Success!"
    }
}

export function formActionError(error){
    return {
        type: FORM_ACTION_SUCCESS,
        error: error
    }
}

export const formAction = (formData) => {
    return async function(dispatch) {
        dispatch(formActionRequest());
        try{
            let response = (await axios.post("http://yourapi.com/form", formData)).data;
            dispatch(formActionSuccess(response));            
        }catch(error){
            dispatch(formActionError(response.error));
        }
    }
}

//formReducer.js

const initState = {
    responseData: {}
};

export function formReducer(state = initState, action){
    // reducer is kept blank since we do not have anything specific
    // for the moment
    return state;
}
    

Throughout this guide, we will refer to the above components to clarify the examples.

Sharing a Single Action Between Multiple Reducers

Assume we are building a complex web app that provides feedback to user actions by means of popup notifications. For example, when the user submits a form, a notification pops up to either confirm the success of the submission or report any errors.

While this sounds trivial at first, a certain complication occurs in implementing with React and Redux. Logically, the Redux action—let's say formAction—should be able to do the following:

  • On dispatching the action, communicate the user input to the API
  • On success, direct the API response data to the relevant reducer to be processed
  • On success, show a confirmation popup notifying the user that the action was a success
  • On error, direct the API error data to the relevant reducer
  • On error, show an error notification to the user notifying the relevant error

The first solution that might come to mind would be to have separate confirmation and error storage in the relevant reducer and have a NotificationComponent listening to these. Below is an outline of such a reducer.

      //formReducer.js

// following shows how notification data can be kept inside the 
// form reducer itself

import { FORM_ACTION_SUCCESS, FORM_ACTION_ERROR} from 'formActions.js';

const initState = {
    error: null,
    message: null
};

export function formReducer(state = initState, action){
    switch(action.type){
        case FORM_ACTION_SUCCESS:
            state.message = action.message;
            return state;
        case FORM_ACTION_ERROR:
            state.error = action.error;
            return state;
    }
}
    

Say we need to have five other such reducers corresponding to various elements of our app. We would end up having error and notification storage defined in each reducer. Further, the NotificationComponent would need to be updated with each new reducer. Ideally, we need a separation of concerns. Thus, we need a pattern where our actions, when dispatched, are caught by multiple reducers: (1) the action's intended reducer, and (2) the notification reducer. In Centralized Error Handing with React and Redux, we discussed how to implement such centralized solutions for error handling. Since implementing notification is only a generalized solution of the above, I will leave you to refer to the above guide which provides more in-depth details on implementation.

Sharing an Action Within Another Action

Another common occurrence is the need to dispatch multiple Redux actions together. For example, let's say that in the above-discussed form, we need to disable the submit button when clicked by the user (to prevent compulsive triggering of the button by the user), and re-enable the button when the API response is received. There are two ways this could be handled.

First, we could use the same logic as before, where we have a UI reducer for the button that listens to a specific set of actions. We include the formActionRequest to the set of listening actions and disable the button when it is dispatched. Then we listen to formActionSuccess and formActionError actions and enable the button when either of those is dispatched. While this is a sound solution, it greatly reduces code readability. Unlike the notification system, the button is not a central requirement, and it doens't need to be handled this way.

Alternatively, we can use separate UI actions declared as disableSubmitButton and enableSubmitButton. And in our formAction, we first dispatch disableSubmitButton before the API request, and on receiving the response from the API we dispatch enableSubmitButton.

      // uiActions.js
export const ENABLE_SUBMIT_BUTTON = "ENABLE_SUBMIT_BUTTON";
export const DISABLE_SUBMIT_BUTTON = "DISABLE_SUBMIT_BUTTON";

export function enableSubmitButton(){
    return {
        type: ENABLE_SUBMIT_BUTTON
    }
}

export function disableSubmitButton(){
    return {
        type: DISABLE_SUBMIT_BUTTON
    }
}

// uiReducer.js

// this reducer is responsible for UI changes in the form
// note that the actual efficiency comes with the ability to separate app logic
// from the UI logic by splitting these into different reducers
import { ENABLE_SUBMIT_BUTTON, DISABLE_SUBMIT_BUTTON} from 'uiAcions.js';

const initState = {
    formSubmit: {
        enabled: true
    }
};

export function uiReducer(state = initState, action){
    switch(action.type){
        case ENABLE_SUBMIT_BUTTON:
            state.formSubmit.enabled = true;
            return state;
        case DISABLE_SUBMIT_BUTTON:
            state.formSubmit.enabled = false;
            return state;
    }
}
    

Now we modify the formAction to utilize the above actions.

      import { enableSubmitButton, disableSubmitButton } from 'uiActions.js';

export const formAction = (formData) => {
    return async function(dispatch) {
        dispatch(formActionRequest());
        dispatch(disableSubmitButton())
        try{
            let response = (await axios.post("http://yourapi.com/form", formData)).data;
            dispatch(formActionSuccess(response));            
        }catch(error){
            dispatch(formActionError(response.error));
        }finally{
            dispatch(enableSubmitButton())
        }
    }
}
    

As shown above, this greatly improves the code readability and prevents the need for maintaining an "action set" on the UI reducer side to listen on. Although the above snippet only demonstrates the usage of it, the actual power of it comes in complex scenarios where multiple such actions need to be dispatched within a single action.

Conclusion

In this guide, we explored beyond the one-to-one mapping concept of Redux actions and reducers. While one-to-one mapping works well in a majority of cases, we explored two practical scenarios where sharing actions and reducers can be more robust than replicating logic in several places.