Search code examples
angularngrx

How to filter ngrx store items in angular?


Hi I am learning to use ngrx.

I am using effects to fetch data.

loadItems$ = createEffect(() =>
this.actions$.pipe(
  ofType(ItemActions.loadItems),
  mergeMap(action =>
    this.defaultService.getItems().pipe(
      map(Items => ItemActions.loadItemsSuccess({ Items })),
      catchError(error =>
        of(ItemActions.loadItemsFailure({ error }))
      )
    )
  )
)
)

Can someone suggest me how to apply a list of filters on the items received by the store?


Solution

  • To filter data in an effect or in a selector you should use normal javascript tools like Array.filter, Array.reduce etc.

    for example if you want to filter them in an effect.

    loadItems$ = createEffect(() =>
        this.actions$.pipe(
            ofType(ItemActions.loadItems),
            mergeMap(action =>
                this.defaultService.getItems().pipe(
                    map(Items => ItemActions.loadItemsSuccess({
                      Items: Items.filter(item => item.active) })), // Array.filter
                    catchError(error =>
                        of(ItemActions.loadItemsFailure({ error }))
                    )
                )
            )
        )
    )
    

    or in selector you can use map operator.

    this.store.select(selectItems).pipe(
      map(items => items.filter(item => item.active)), // Array.filter
    );