Molloch
Molloch

Reputation: 2381

Ngrx effects not waiting for required data after refactoring

I had a working app using the original reducers, actions and effects of ngrx 7. Some of my effects read a value from the store using withLatestFrom, which is populated by another action/effect. They then use the id to load child data from an api. This has always worked as expected, the child effects wait for the parent data to be populated before executing.

createEffect(() => 
  this.action$.pipe(
    ofType(accountActions.loadAccountAlerts),
    withLatestFrom(this.store.pipe(fromAccount.getAccountId)),
    mergeMap(([action, id]) => //Downloads Data from Api ands dispatches a success action)
)

Today I refactored the reducer referenced by fromAccount to use createReducer using the new ngrx 8 syntax. Now suddenly my effects are no longer waiting for a value in withLatestFrom, they get the value of getAccountId as null.

Instead of loading data once the accountId is populated, all of the effects now run before the action that populates accountId is completed. I assume the way the reducer is initialized has changed, but what should I do to return to the original functionality.

Should I have ever been assuming that withLatestFrom against the store would work like that?

Upvotes: 0

Views: 719

Answers (1)

Will Alexander
Will Alexander

Reputation: 3571

If you have a default value in your store (BTW strongly suggest using selectors and not piping the whole store), it will be emitted, even if it is null. To ensure you have a value, use:

withLatestFrom(this.store.pipe(fromAccount.getAccountId).pipe(
  filter(id => !!id)
))

EDIT: NgRx calls the reducer first, then the effect. It sounds like you might have some other magic going on in the reducer, or perhaps this effect is reacting to the wrong action. Do you have a loadAccountAlertsSuccss action?

Upvotes: 1

Related Questions