user2816626
user2816626

Reputation: 83

Ngrx Effects withLatestFrom causes an exception

I am trying to dispatch an action that will load books depending on selected publisher.

Here is the sample of the effect class:

@Injectable()
export class LibraryEffects {
    @Effect({})
    bookRequest = this.actions.pipe(
        ofType(BOOK_LIST_REQUEST),
        withLatestFrom(
            this.store.pipe(
                select(selectBookshop),
                map(bookshop => bookshop.library.publisher),
            )
        ),
        map(([action, publisher]) => {
            window.console.log(action, publisher);
            return new BookRequestSuccess();
        })
    );

    constructor(
        private actions: Actions,
        private store: Store<AppState>
    ) {}
}

When application starts storage does not contain nor 'bookshop' neither 'library' properties in it which are getting filled later with user actions. After that user triggers 'BOOK_LIST_REQUEST' action and should retrieve appropriate list of books.

But an exception occurs as soon as effect is registered even without calling 'BOOK_LIST_REQUEST' action that should subscribe to 'library' property in storage:

core.js:15714 ERROR TypeError: Cannot read property 'library' of null

This seems weird as if effect is registering an observable to the storage on effect registration in module and not on calling 'BOOK_LIST_REQUEST' action.

What could be an issue here ? Am i doing reading from storage in this effect somehow wrong?

Upvotes: 1

Views: 1067

Answers (1)

user2816626
user2816626

Reputation: 83

Seems like this issue is fixed if withLatestFrom is wrapped in concatMap operator as it is done in ngrx documentation example (collection.effects.ts).

        ofType(BOOK_LIST_REQUEST),
        concatMap(action => of(action).pipe(
          withLatestFrom(this.store.pipe(
            select(selectBookshop), 
            map(bookshop => bookshop.library.publisher)
         )
       )

Upvotes: 2

Related Questions