Search code examples
angularngrx

my subset selector using Ngrx isn't working


i'm using Angular 17 with ngrx.

I have the following selectors that work fine:

export const getPhotoState = createFeatureSelector<ProductResponse>('selectedPhotos');

export const selectPhotos = createSelector(getPhotoState, (state: ProductResponse) => { return state.results });

export const PhotoCount = createSelector(getPhotoState, (state: ProductResponse) => { return state.item_Count });

I dont want to write another effect/reducer to go off to the server as I just want to get a subset of the data already returned.

I have written the following:

export const XboxPhotos = createSelector(selectPhotos, (reducedPhotos) => {
  return xboxPhotos('xbox', reducedPhotos)
})

function xboxPhotos(key: string, array: any) {
  return array.reduce((all: Product[], current: Product) => {
    if (current.platform == key) {
      all.push(current);
    }
  }, []) as Product[]
}

I receive an error of :

Cannot read properties of undefined (reading 'push')

reducedPhotos is Product[]


Solution

  • Return the value after operations

    function xboxPhotos(key: string, array: any) {
      return array.reduce((all: Product[], current: Product) => {
        if (current.platform == key) {
          all.push(current);
        }
        return all; // <- changed here
      }, []) as Product[]
    }