angulartypescriptngrxngrx-entity

How to sort entities by any property in ngrx


In the documentation I found a simple example using sortComparer, the problem is that we only sort by name and if I want to do it by different properties, I have to somehow provide information about the key / property. I know that I can keep sorting information in each entity, but I don't want to duplicate it ... I prefer to get it from the main state... Can I somehow inject a service that will deliver the sort state from the main state?

reducer.ts

export function advancedSorting(a, b): any {
  const sortState = { key: 'name', order: 1 }; // temporary mock - get sort state from main store
  const itemA = a[sortState.key];
  const itemB = b[sortState.key];
  return itemA < itemB
    ? -1 * sortState.order
    : itemA > itemB
    ? sortState.order
    : 0;
}

export const adapter: EntityAdapter<ProductDetails> =
  createEntityAdapter<ProductDetails>({
    sortComparer: advancedSorting
  });

export const initialState: ProductsState = adapter.getInitialState({
  productType: null,
  productTags: [],
  sort: {
    key: 'name',
    order: 1
  }
});

Solution

  • Reducers are pure, and so is @ngrx/entity. You also can't reference another reducer (state) from within a reducer.

    Instead, I recommend using a selector that retrieves both state slices and orders the collection in the selector.