Created
February 21, 2020 16:26
-
-
Save johanquiroga/004ef3946f9a5ffb5c85c7e97a669b49 to your computer and use it in GitHub Desktop.
Utilities to handle common reducer actions when dealing with normalized data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import set from 'lodash/fp/set'; | |
import get from 'lodash/fp/get'; | |
import omit from 'lodash/fp/omit'; | |
import pipe from 'lodash/fp/pipe'; | |
const removeFromArray = (array, target) => array.filter(n => n !== target); | |
export const addEntity = (state, entity, id) => { | |
return pipe( | |
set(['entities', id], entity), | |
set('ids', state.ids.concat(id)), | |
)(state); | |
}; | |
export const removeEntity = (state, id) => { | |
return pipe( | |
omit(`entities.${id}`), | |
set('ids', removeFromArray(state.ids, id)), | |
)(state); | |
}; | |
export const addIdToChildren = (state, entityId, property, childId) => { | |
const path = ['entities', entityId, property]; | |
const children = get(path)(state); | |
return set(path, children.concat(childId), state); | |
}; | |
export const removeIdFromChildren = (state, entityId, property, childId) => { | |
const path = ['entities', entityId, property]; | |
const children = get(path)(state); | |
return set(path, removeFromArray(children, childId), state); | |
}; | |
// Eample | |
// someReducer.js | |
/* | |
import { RESOURCE_CREATE, RESOURCE_DELETE } from '../actions/resource-actions'; | |
import { addEntity, removeEntity } from './_utilities'; | |
const resourceReducer = (state = initialState, action) => { | |
if (action.type === RESOURCE_CREATE) { | |
const { resource, resourceId } = action.payload; | |
return addEntity(state, resource, resourceId); | |
} | |
if (action.type === RESOURCE_DELETE) { | |
const { resourceId } = action.payload; | |
return removeEntity(state, resourceId); | |
} | |
return state; | |
}; | |
export default resourceReducer; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment