How to update state with an array via NGRX reducer in Angular?

752 Views Asked by At

I want to update my state using a ngrx reducer but I'm getting an compilation error.

For context. The user submits a worklog on a form, and I want this worklog to be added to the worklogs array on the state.

Here is the structure of my state:

export declare interface Outreach {
  outreach: CaseState|null;
}

export declare interface CaseState {
  outreachCaseId: string;
  worklogs: WorklogCase[];  // <- I want to add the new worklog here
}

export declare interface WorklogCase {
  worklogId: string;
  username: string;
  details: string;
}

The reducer:

const initialState: OutreachState = {
  outreach: null,
}

export const outreachDetailsReducers = createReducer<OutreachState>(
    initialState,
    on(outreachActions.addWoklogSuccess,
    state, {worklog}) => ({...state, worklogs: [...worklog]})),

I think I have the sintax wrong some how on the last line of the reducer. Any help?

1

There are 1 best solutions below

1
Steve Holgado On

You have your worklogs state nested under an outreach property that could be null.

Therefore, you will have to check that the outreach property is not null before updating its worklogs array with the new worklog:

export const outreachDetailsReducers = createReducer<OutreachState>(
  initialState,
  on(
    outreachActions.addWoklogSuccess,
    state, { worklog }) => ({
      ...state,
      outreach: state.outreach !== null
        ? {
            ...state.outreach,
            worklogs: [...state.outreach.worklogs, worklog]
          }
        : null,
      }
  )
),

Ideally you should try to make your state as flat as possible to avoid the complexities that come with nesting.