Hongbo Miao Hongbo Miao - 2 months ago 15
TypeScript Question

Cannot read property 'type' of undefined (ngrx)

I am using ngrx. I got error


Cannot read property 'type' of undefined


This is part of my codes:

@Effect() foo$ = this.actions$
.ofType(Actions.FOO)
.withLatestFrom(this.store, (action, state) => ({ action, state }))
.map(({ action, state }) => {
if (state.foo.isCool) {
return { type: Actions.BAR };
}
});

Answer

This issue is little tricky since it is not easy to locate the issue based on the error.

In this situation, when state.foo.isCool is false, no action is returned.

So changing to something like this will solve the issue:

@Effect() foo$ = this.actions$
    .ofType(Actions.FOO)
    .withLatestFrom(this.store, (action, state) => ({ action, state }))
    .map(({ action, state }) => {
      if (state.foo.isCool) {
        return { type: Actions.BAR };
      }

      return { type: Actions.SOMETHING_ELSE };
    });