Skip to content

Instantly share code, notes, and snippets.

@soker90
Last active June 24, 2020 21:22
Show Gist options
  • Save soker90/8f67ccf8dccb3c9aadfa5baff335bdda to your computer and use it in GitHub Desktop.
Save soker90/8f67ccf8dccb3c9aadfa5baff335bdda to your computer and use it in GitHub Desktop.
Create reducer with default setPayload
import { setPayload } from './setPayload';
/**
* Busca si el handler dado es una funcion,
* si lo es devuelve la función, si no lo es
* devuelve una función setPayload por defecto
* @param {function | string} actionHandler
* @returns {function}
* @private
*/
const _getUpdatedStateFunction = actionHandler => (
typeof actionHandler === 'function'
? actionHandler
: setPayload
);
/**
* Comprueba si existe el action handler, si no existe devuelve
* el estado sin modificar, si existe devuelve el estado modificado
* por el handler
* @param {Object} oldState
* @param {Object} action
* @param {Function | string} actionHandler
* @returns {Object}
* @private
*/
const _getNewState = (oldState, action, actionHandler) => (
actionHandler
? _getUpdatedStateFunction(actionHandler)(oldState, action)
: oldState
);
/**
* Create reducer with the new style from {key: value}
* @param {Object} INITIAL_STATE
* @param {Object} ACTION_HANDLERS - typical switch
* @returns {function(Object, Object): Object}
*/
export const createReducer = (INITIAL_STATE, ACTION_HANDLERS) => (
(state = INITIAL_STATE, action) => (
_getNewState(state, action, ACTION_HANDLERS[action.type])
)
);
import { createReducer } from 'store/utils';
import {
MY_ACTION2
} from './types';
const INITIAL_STATE = {
myState: null,
};
const ACTION_HANDLERS = {
MY_ACTION,
MY_ACTION2: () => INITIAL_STATE,
};
export default createReducer(INITIAL_STATE, ACTION_HANDLERS);
/**
* Devuelve un estado con los cambios del payload dado
* @param state
* @param payload
*/
export const setPayload = (state, { payload }) => ({ ...state, ...payload });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment