lore-extract-reducer
Extracts the reducer blueprint for a model to src/reducers
Extracts the reducer blueprint for a model to src/reducers
CLI command to extract the byId reducer for a given model into your project.
lore extract reducer [model]/byId
lore extract reducer post/byId
import { ActionTypes } from 'lore-utils';
import _ from 'lodash';
/*
* byId Reducer Blueprint
*/
function addOrUpdateById(nextState, payload) {
const id = payload && payload.id;
let existingModel = null;
if (id) {
existingModel = nextState[id];
if (existingModel) {
nextState[id] = _.assign({}, payload, {
cid: existingModel.cid
});
} else {
nextState[id] = payload;
}
}
return nextState;
}
function removeById(nextState, payload) {
const id = payload && payload.id;
if (id) {
delete nextState[id];
}
return nextState;
}
export default function byId(state, action) {
state = state || {};
let nextState = _.assign({}, state);
switch (action.type) {
case ActionTypes.add('post'):
return addOrUpdateById(nextState, action.payload);
case ActionTypes.update('post'):
return addOrUpdateById(nextState, action.payload);
case ActionTypes.remove('post'):
return removeById(nextState, action.payload);
case ActionTypes.fetchPlural('post'):
action.payload.data.forEach(function(datum) {
addOrUpdateById(nextState, datum);
});
return nextState;
default:
return nextState
}
};