0
votes

My application is built in angular with NGRX. I dispatch a getUser() action to retrieve the user ID. I would like to wait for the user ID to return and then fetch all items for that user from the database service.

How can this best be achieved? I was thinking of creating an action & effect called getInitialData that would chain actions. I have two reducers one for the user and one for the items.

Should I create the getInitialData action + service in the users reducer OR should I be creating a new reducer?

2

2 Answers

0
votes

This question is primarily opinion based, but I'll give you one way this could be solved with ngrx/effects.

What people often miss is that effects don't have to be waiting for actions to be triggered, any observable is a valid source to trigger an effect.

For example, have a look at the effect below. It will output 0,1,2,3... indefinitely. The source here is the normal interval operator from rjxs.

  timerEffect$ = createEffect(() =>
    interval(1000)
      .pipe(
        tap((val) => {
          console.log(val);
        })
      ), {dispatch: false}
  );

Perhaps you see where I'm going with this already, but a simple subject or observable of the authenticated users ID could be used to trigger effects.

  loadUserData$ = createEffect(() =>
    this.userId$
      .pipe(
        mergeMap((userId) => {
          return [action1, action2, action3] // A bunch of actions that loads relevant data
        })
      )
  );

You can of course split it up even more, but this would do the work.

As for what is best practice, I cannot say. The question is to broad and very opinion based.

0
votes

The way I solve this, is:

User Actions:

  • GetUser
  • GetUserSuccess (payload: {userID: string )
  • GetUserFail (payload: {response: any})

UserItems actions:

  • GetUserItems (payload:{ userId: string})
  • GetUserItemsSuccess (payload:{items: any})
  • GetUserItemsFail (payload: {response: any})

Then I register an effect that waits for the GetUserSuccess action which returns the new action: GetUserItems.

Note: You can listen for GetUserSuccess action from an effect. The reducer will be called first so when the effect is called the store is already updated with the userId (in case you need to access the store)

I hope it helps