Reputation: 11
I have two reducers that handle two distinct parts of my scope (dimensions and examples). These two constructs represent two distinct types of object; however, they share some functionality, such as create, delete, save, etc.
Is there a best practices for sharing functionality between these reducers? I am currently doing something like:
Reducer 1
case ADD_EXAMPLE:
const defaultDimension = Immutable.Map({
id: 1,
title: Immutable.Map({ value: '', error:"empty", dirty: false}),
description: Immutable.Map({ value: '', error:"empty", dirty: false}),
options: Immutable.Map({}),
...
});
return fxAdd(state, defaultDimension);
Reducer 2
case ADD_EXAMPLE:
const defaultExample = Immutable.Map({
id: 1,
title: Immutable.Map({ value: '', error:"empty", dirty: false}),
description: Immutable.Map({ value: '', error:"empty", dirty: false}),
selections: Immutable.Map({}),
...
});
return fxAdd(state, defaultExample);
Reducer Common - called from both reducers.
export function fxAdd(state, object) {
let lastID = 0;
if (state.size!=0) {
lastID = state.maxBy((obj) => obj.get('id')).get('id');
}
return state.push(object.set('id', lastID+1));
}
This seems kind of hacky given that these actions are essentially the same with only the default object being different in each case. More importantly; this way requires 2 action creators, 2 action constants.
Upvotes: 1
Views: 270
Reputation: 67439
This actually seems entirely acceptable. As Dan Abramov has pointed out several times, reducers are just functions, and you can decompose or combine them any way you want. Your approach seems very reasonable, and a good example of splitting out common behavior.
Upvotes: 1