Many experts recommend consolidating the logic in action creators to streamline the reducer's logic.
Picture a basic (normalized) state:
const initialState = {
parent: {
allIds: [0],
byId: {
0: {
parentProperty: `I'm the parent`,
children: [1, 2]
}
}
},
children: {
allIds: [1, 2],
byId: {
1: {
childrenProperty: `I'm the children`
},
2: {
childrenProperty: `I'm the children`
}
}
}
}
If I were to delete the parent, I would also need to delete the associated children.
An example of an action creator for this scenario:
function removeParent(parentId) {
return {type: 'REMOVE_PARENT', payload: {parentId}};
}
and
function removeChild(childId) {
return {type: 'REMOVE_CHILD', payload: {childId}};
}
Currently, my approach with redux-thunk looks like this:
function removeParentAndChildren(parentId) {
return (dispatch, getState) {
const childrenIds = getChildIds(getState(), parentId);
const childActions = childrenIds.map(removeChild);
const combinedAction = combineActions([
removeParent(parentId),
...childActions
], 'REMOVE_PARENT_AND_CHILDREN');
dispatch(combinedAction);
}
}
This method allows me to bundle smaller actions into one larger action, keeping the reducer logic straightforward by simply removing keys from objects.
On the flip side, using redux-thunk just for retrieving state information is frowned upon as an anti-pattern.
How do you handle similar challenges? Could tools like redux-saga be beneficial in this context?