Home > database >  How to sort entities by any property in ngrx
How to sort entities by any property in ngrx

Time:10-28

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
  }
});

CodePudding user response:

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.

CodePudding user response:

I cant add a comment to @timdeschryver's answer but I agree with him.

Just to add my 2-cents and to elaborate more.

From my understanding, the best practice for your situation, since it seems like your sorting is more related to the 'view' of your app and not the actual state of your entities, its best to sort it in the selector. Because your entity is just meant to hold information related to the entity, not how it is 'viewed'.

Personally, half the time, i dont have a need to sort my entities because i do all the sorting in the selector, since it might relate to a paginator somewhere, or some other state in my app.

  • Related