a React-Redux Action Update Multiple Reducers

each action is being dispatched to all the reducers, the reducers may decide whether they wish to use the action to update something or not

What you want is to

const updateAll = params => {
    return {type: 'UPDATE_PARAMS', payload: params}
}

and then use it in different reducers like

const newReducer = (state= initialState, action) => {
   switch(action.type) {
      case 'UPDATE_PARAMS': return {
         ...state,
         // do some things here
      }
      ...
      default: return state;
   }
}

const userReducer = (state= initialState, action) => {
   switch(action.type) {
      case 'UPDATE_PARAMS': return {
         ...state,
         // do some things here
      }
      ...
      default: return state
   }
}

From react-redux 7.1, you can leverage the batch API to dispatch all the actions on a single re-render. From the docs you can do something like:

import { batch } from 'react-redux'

function myThunk() {
  return (dispatch, getState) => {
    // should only result in one combined re-render, not two
    batch(() => {
       dispatch(newsAction(newsParam))
       dispatch(userAction(newsParam))
       dispatch(notifyAction(newsParam))
    })
  }
}

One way of doing this could be to fire batched actions. So you can have three different actions, one per reducer, and have a main action that takes care of all these three subsequently (or just add two actions under the first one). This can be done by using thunks (thunk middleware). To do something like, assuming they're async:

const updateAllNewsStuff = newsParam => {
  return dispatch => {
    dispatch(newsAction(newsParam))
    dispatch(userAction(newsParam))
    dispatch(notifyAction(newsParam))
  }
}

You could probably also look at this plugin to fire batched actions: https://github.com/tshelburne/redux-batched-actions

Tags:

Reactjs

Redux