import { Action } from "../types"; import { getType } from "typesafe-actions"; import { fetchRecipesFulfill, postCookingSessionFulfill, postRecipeFulfill, } from "../actions"; import { Dict, Entities } from "../entities"; const initialState: Entities = { recipes: {}, cookingSessions: {}, ingredients: {}, }; export default function entitiesReducer(state = initialState, action: Action) { switch (action.type) { case getType(fetchRecipesFulfill): case getType(postRecipeFulfill): case getType(postCookingSessionFulfill): { const { entities } = action.meta; return Object.keys(state).reduce( (state, key) => ({ ...state, [key]: mergeEntities(state[key], entities[key]), }), state ); } default: return state; } } function mergeEntities(entitiesA: Dict = {}, entitiesB: Dict = {}) { return Object.keys(entitiesB).reduce( (acc, key) => ({ ...acc, [key]: acc[key] ? { ...acc[key], ...entitiesB[key], } : entitiesB[key], }), entitiesA ); }