0

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 Answers1

1

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.

Steve Holgado
  • 11,508
  • 3
  • 24
  • 32
  • This is the correct answer - but you can also take a look at ngrx-immer to make it easier to update state. https://github.com/timdeschryver/ngrx-immer – timdeschryver Dec 07 '21 at 16:29