redux-utilities/redux-actions

Reducer composition using redux actions

nicolasmsg opened this issue · 0 comments

I'm searching an elegant and simple way to do reducer composition using redux-actions

In my project I need to run several Control in same time. So instead of create a single big ControlsReducer who manage everything i would like to split the Controls and Control logic so they have their own reducer.

The following code works, but i have to define in my controlsReducer every controlActions he has to forward to his ControlReducers. Is there a better/simpler way to do this ?

Thanks

`

  // --------------- ControlsActions.js
  import { createActions } from 'redux-actions';

  export const controlsActions = createActions({
    CONTROLS: {
      ADD_CONTROL: x => x,
    }
  })

  // --------------- ControlActions.js
  import { createActions } from 'redux-actions';

  export const controlActions = createActions({
    CONTROL: {
      UUID_RECEIVED: x => x,
    }
  })

  // --------------- ControlsReducer.js

  import { handleActions, combineActions } from 'redux-actions';
  import { INITIAL_STATE as CONTROL_INITIAL_STATE, controlReducer } from './controlReducer'
  import { controlsActions as actions } from './controlsActions';
  import { controlActions } from './controlActions';


  const actionsToCombine = [
    controlActions.control.uuidReceived
  ]

  const INITIAL_STATE = {
    controls: []
  };

  export const controlsReducer = handleActions(
    {
      [combineActions(...actionsToCombine)]: controlAction,
      [actions.controls.addControl]: addControl,
    },
    INITIAL_STATE
  );

  function controlAction(state, action) {
    let copy = state.controls.slice()
    copy[action.payload.index] = controlReducer(state.controls[action.payload.index], action);
    return {
      ...state,
      controls: copy
    }
  }

  function addControl(state) {
    const updatedControls = state.controls.concat([CONTROL_INITIAL_STATE])
    return {
      ...state,
      controls: updatedControls
    };
  }

  // --------------- ControlReducer.js
  import { handleActions } from 'redux-actions';
  import { controlActions as actions } from './controlActions';

  export const INITIAL_STATE = {
    id: null,
    uuid: null,
  };

  export const controlReducer = handleActions(
    {
      [actions.control.uuidReceived]: uuidReceived,
    },
    INITIAL_STATE
  );

  function uuidReceived(state, action) {
    return {
      ...state,
      uuid: action.payload.uuid
    };
  }

`