Storing Normalized data into Redux

Viewed 87

When making my API request, I get a deeply nested object back from the server, from reading up on this it's bad practice for Redux to store nested object data, therefore, I am using Normalizr on that object which returns me many different entities.

The issue I am facing is when making that request inside my Action. How I can store each entity into a different reducer effectively.

action.ts

export const fetchClaim = (claimId: string) => async (dispatch: any) => {
    dispatch({ type: REQUEST_CLAIM, payload: true });

    try {
        const response = await req.get(`claim/${claimId}`);

        const normalizedData = normalize(response.data, Claim);

        dispatch({ type: SET_LIABILITY, payload: normalizedData.entities.LiabilityType });
        dispatch({ type: SET_CLAIM_STATUS, payload: normalizedData.entities.ClaimStatus });
        dispatch({ type: SET_CLAIM, payload: normalizedData.entities.Claim });
        dispatch({ type: SET_ACTIONS, payload: normalizedData.entities.Actions });
    } catch (e) {}
}

I then have an index.ts file inside my reducer folder which combines the reducers.

import  { combineReducers } from 'redux';

import claimReducer from './claimReducer';
import actionReducer from './actionReducer';
import liabilityReducer from './liabilityReducer';
import claimStatusReducer from './claimStatusReducer';

export default combineReducers({
    claim: claimReducer,
    actions: actionReducer,
    liability: liabilityReducer,
    claimStatus: claimStatusReducer
});

Finally, each reducer looks identical in terms of storing its data.

import { LiabilityActionTypes, LiabilityState } from "../types/Liability";

const INITIAL_STATE: LiabilityState = {
    liability: null
}

// State - Returns what the state was when this reducer was previously ran.
// Action - This is what the action creator dispatched.
export default (state = INITIAL_STATE, action: LiabilityActionTypes): LiabilityState => {
    switch (action.type) {
        case 'SET_LIABILITY':
            return { ...state, liability: action.payload };
        default:
            return state;
    }
}

My question is, it doesn't seem right that if i have around 40 entities, that I need to call dispatch 40 times inside the fetchClaim action. Is there a best practice to achieve this?

0 Answers
Related