Search code examples
angular6ngrxngrx-store

Making http call and fetching data using selectors in ngrx


I am a newbie in ngrx and was trying to implement store in my application. I came across one scenario like on the load of my page, I am making an http request and trying to fetch the data from selector. Since http is async and since I am immediately calling the selector method which is throwing an error.

PFB Component code which is triggering a load dispatcher and I was expecting the results in this.products$

  ngOnInit() {

    this.store.dispatch(new productActions.Load());
    this.products$ = this.store.pipe(select(fromProducts.getProducts));
    that.initForms();
  }

My effects

  @Effect()
    loadProducts$: Observable<Action> = this.actions$.pipe(
      ofType(productActions.productActionTypes.Load),
      mergeMap(action =>
        this.productService.getProductData().pipe(
          map(products=> (new productActions.LoadSuccess(products))),
          catchError(err => of(new productActions.LoadFail(err)))
        )
      )
    );

Selector

export const getProducts = createSelector(
    getProductFeatureState,
    state => state.products
);

The error I am getting is triggering from the above selector method

ERROR TypeError: Cannot read property 'products' of undefined

Is there a way to handle this ? Please share your thoughts on this

Tia


Solution

  • Setting an empty initial state fixed the issue