vineanova-redux-artifacts
Version:
## Overview
98 lines (92 loc) • 2.31 kB
JavaScript
import omit from "lodash/omit";
const initialState = {
isLoading: false,
hasError: false,
isLoaded: false,
error: null,
data: {},
byId: {},
allIds: [],
};
const createNamedReducer = (reducerName = '') =>
function counter(state = initialState, action) {
const { name, payload } = action;
if (name !== reducerName) return state;
switch (action.type) {
case `FETCHING`:
return {
...state,
isLoading: true,
isLoaded: false,
hasError: false,
error: null,
};
case `SUCCESS`:
return {
...state,
isLoading: false,
isLoaded: true,
data: payload,
};
case `MERGE_ALL_IDS`:
const {byId, allIds} = payload;
return {
...state,
isLoading: false,
isLoaded: true,
byId: {
...state.byId,
...byId,
},
allIds: [...new Set([...state.allIds,...allIds])],
};
case 'DELETE_BY_ID':
const { id } = payload;
if(!id) return state;
const allIdsFiltered = state.allIds.filter(f=> f !== id);
return{
...state,
byId:{
...omit(state.byId, `${id}`)
},
allIds: allIdsFiltered,
}
/** update partial entities for post/put methods **/
case 'UPDATE_PARTIAL_ENTITY':
const { entityId, key, value } = payload;
if(!Array.isArray(state.data)) return state;
if(!key) return state;
if(!entityId) return state;
const newEntities = state.data.map(entity => {
if (entity.id === entityId) {
return {
...entity,
[key]: value,
};
}
return entity;
});
return {
...state,
data: newEntities,
};
case `ERROR`:
return {
...state,
isLoading: false,
isLoaded: true,
hasError: true,
error: payload,
};
case 'CLEAR_DATA':
return {
...state,
isLoaded: false,
hasError: false,
data: {},
};
default:
return state;
}
};
export default createNamedReducer;