Search code examples
angularngrx

Passing value into store as part of dispatch action returning undefined


I'd like to pass in a value into my store to update the current value.

What is the best way of doing it?

I've tried the below and setSelectedCourseContentUid is set to undefined. In my component:

  setSelectedCourseContentUid(uid: string): void {
    console.log(uid);
    this.store.dispatch(builderActions.hideAddContentMenu());
    this.store.dispatch(
      builderActions.setSelectedCourseContentUid({ selectedCourseContentUid: uid })
    );
  }

builder.actions.ts

export const setSelectedCourseContentUid = createAction(
  '[Builder] Set Selected Course Content Uid',
  props<{ selectedCourseContentUid: string }>()
);

builder.reducer.ts

export const builderReducer = createReducer(
  initialState,
  on(BuilderActions.setSelectedCourseContentUid, (state, { selectedCourseContentUid }) => {
    return {
      ...state,
      selectedCourseContentUid,
    };
  })
);

Solution

  • Declare props on your action:

    export const setSelectedCourseContentUid = createAction('[Builder] Set Selected Course Content Uid', props<{ uid: String}>);
    

    then access in your reducer:

    export const builderReducer = createReducer(
      initialState,
      on(BuilderActions.setSelectedCourseContentUid, (state, {uid}) => {
        return {
          ...state,
          selectedCourseContentUid: uid,
        };
      })
    );