I have individual users for which an enthusiasm value can be in/decremented. After this I want updated the overall enthusiasm level (globalEnthusiasmLevel) as wel, the sum of individual enthusiasm integers (per user).
I have everything I need to know to update the overall value at the time the individual value is being processed (action > reducer), however I want it to be a separate action for the sake of practice purposes.
export function enthusiasm(state: StoreState, action: UsersAction): StoreState {
let globalEnthusiasmLevel: number;
switch (action.type) {
case INCREMENT_ENTHUSIASM:
state.users = state.users.map((user: UserType) => {
if (user._id === action.payload._id) {
user.enthusiasmLevel = user.enthusiasmLevel + 1;
}
return user;
});
globalEnthusiasmLevel = state.globalEnthusiasmLevel + 1;
return { ...state, globalEnthusiasmLevel };
case DECREMENT_ENTHUSIASM:
const users: UserType[] = state.users.map((user: UserType) => {
if (user._id === action.payload._id) {
globalEnthusiasmLevel = (user.enthusiasmLevel > 0 ) ? state.globalEnthusiasmLevel - 1 : state.globalEnthusiasmLevel;
user.enthusiasmLevel = user.enthusiasmLevel - 1;
user.enthusiasmLevel = Math.max(0, user.enthusiasmLevel);
}
return user;
});
return { ...state, ...users, globalEnthusiasmLevel };
case STORE_USERS:
return { ...state, users: action.payload };
case SET_GLOBAL_ENTHUSIASM:
return { ...state, globalEnthusiasmLevel: action.payload };
default:
return state;
}
- What would be the best approach to dispatch an action after an acion?
- is it wise to separate
STORE_USERS
andSET_GLOBAL_ENTHUSIASM
into a different reducer?