10

I have ngrx application, and I can't get the value from a selector in the effect, by the payload I sent in the component.

I write an example code of what I deal with:

This is my state, a simple docs array in it.

export const initialState = {
  docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};

export const reducer = createReducer(
  initialState,
);

I dont handle any action for this questions, this is not the issue.

In my component I get the array using a selector:

docs$ = this.store.pipe(select(fromStore.getAllDocs));

{{docs$ | async | json}}

the reducer:

export const selectDocsState = createFeatureSelector("docs");

export const selectDocsStatusState = createSelector(
  selectDocsState,
  state => state["docs"]
);

export const getAllDocs = createSelector(
  selectDocsStatusState,
  getDocs
)

I also have a selector to get by id:

{{docsById$ | async | json }}

docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));

in the reducer:

export const getById = createSelector(
  selectDocsStatusState,
  getDocs,
  (state, docs, props) => {
    console.log({ props });
    return docs.docs.docs.filter(d => d.id === props.id);
  }
)

So far everything good. I get the docs array and display it.

Now, in my component I dispatch some action and catch by effect:

this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });

And in the effect I want to know if this id is in the store or not.

So I use withLatestFrom from rxjs with the getById selector.

withLatestFrom((a: any) =>
  this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),

The problem is i'm not getting the value from the selector instend I get the store instance.

tap(v => {
  console.log({ v });
}),

The full effect:

getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a),
      tap(a => {
        console.log({ a });
      }),
      withLatestFrom((a: any) =>
        this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
      ),
      tap(v => {
        console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
  );

Here is my full example in stackbliz.

What do I missing here?

1

3 Answers 3

23

Warning - I’d use concatLatestFrom as per ngrx docs and Vincent’s answer. I don’t think this should be upvoted / accepted answer but can’t delete.


Original post:

This is covered in the NgRx Docs - Incorporating State but I found Brandon Roberts github comment more useful:


There are two predominant things you do when listening to an action after using the ofType operator:

actions.pipe(
 ofType('SOME_ACTION')
 someMap(action => doSomething(action))
)

and

actions.pipe(
 ofType('SOME_ACTION'),
 withLatestFrom(store.select(someThing)),
 someMap(([action, latest]) => doSomething(action, latest))
)

These have two different behaviors as far as effects are concerned. The first one doesn't do anything until the action is dispatched, which is what it should do.

The second one immediately subscribes to the withLatestFrom whether the action is dispatched yet or not. If that state used by the selector is not initialized yet, you could get an error you're not expecting. In order to make it "lazy" you end up having to nest it within a flattening observable operator.

actions.pipe(
 ofType('SOME_ACTION'),
 someMap(action =>
  of(action).pipe(
    withLatestFrom(store.select(someThing)),
    someMap(([action, latest]) => doSomething(action, latest))
   )
)

Applying this gives the following:

  getDoc$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(fromDocs.getDocument),
      switchMap(action =>
        of(action).pipe(
          withLatestFrom(
            this.store.select(fromDocs.getById, { id: action.payload.id })
          ),
          map(([action, latest]) => {
            return fromDocs.someAction();
          })
        )
      )
    );
  });

Stackblitz

3
  • 1
    Is this due to the refactoring from using chained methods to using pipe. The argument list being immediately evaluated in the call to pipe instead of each function call in the chain controlling when the next call occurs. If so I would say this was a refactoring that actually made the design worse instead of better.
    – Neutrino
    Feb 1, 2021 at 19:43
  • 3
    This was freaking golden, thank you for sharing. I had an effect that needed to access a store that wasn't initialized yet, this saved the day. May 6, 2021 at 15:41
  • See (and upvote) answer re concatLatestFrom which looks better than mine Jan 27, 2022 at 17:54
9

Use concatLatestFrom from Ngrx (lazy version of withLatestFrom) to mitigate the situation where the original state has not been initiated before needed.

import {Actions, concatLatestFrom, createEffect, ofType} from '@ngrx/effects';

concatLatestFrom(() => this.store.select(fromDocs.getById, { id: action.payload.id }),
      map(([action, latest]) => {
        return fromDocs.someAction();
      })
1
  • This is a better solution and reduces errors. We are using this throughout our application. Nov 18, 2021 at 8:54
0

withLatestFrom doesn't take a composite function, it takes a secondary observable source.

What you can do is use switchMap to switch to the new stream and see its value.

Try:

getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a), // does nothing
      tap(a => {
        console.log({ a });
      }),
      switchMap((a: any) => this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))),
      tap(doc => {
        // can switch this tap to a map and see if there is a value then return this, if not then make an API call
        console.log(doc);
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
2
  • No.. I also want the action object, so I use withLatestFrom, to get the action and the lastest from store...
    – Jon Sud
    Feb 18, 2020 at 15:08
  • SwitchMap takes a composite function, so you can have a handle on the action as an argument (a: any) and switch to the latest value in the store.
    – AliF50
    Feb 18, 2020 at 15:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.