0

I have a response from backend like this:

[{ id: 4, name: 'Andrew'},
 {id: 3, name: 'Rebecca'},
 {id: 2, name: 'Joseph'},
 {id: 1, name: 'Kristin'}]

The order is by descending id. From the last one to first one.

I have an entityAdapter defined in this way:

export const folderAdapter: EntityAdapter<Person> = createEntityAdapter<Person>({
   selectId: person => person.id,
   sortComparer: false,
});

into the reducer I created this function:

  on(PeopleActions.loadAllPeople, (state, action): PeopleState => {
return {
  ...state,
  people: adapter.addMany(action.people, state),
};

}),

when I go to see my state I have this situation:

ids:[4,3,2,1],
entities: {1: {id: 1, name: 'Kristin'}, 2: {id: 2, name: 'Joseph'}, 3: {id: 3, name: 'Rebecca'}, 4: { id: 4, name: 'Andrew'}}
}

This also happen into the ngFor. I tried to set return value to zero in ngfor keyvalue but nothing change. How can I change the order in entities? is there a particular property?

Andy88
  • 647
  • 2
  • 9
  • 21

1 Answers1

0

The EntityAdapter has the parameter sortComparer for this exact purpose.

All you need it to instead of using

  sortComparer: false

you give it the function you would like to have sorting your entity ids

  sortComparer: (a ,b) => a.id - b.id

As per ngrx's docs:

If provided, the state.ids array will be kept in sorted order based on comparisons of the entity objects, so that mapping over the IDs array to retrieve entities by ID should result in a sorted array of entities.

If not provided, the state.ids array will not be sorted, and no guarantees are made about the ordering. In other words, state.ids can be expected to behave like a standard Javascript array.

The Fabio
  • 5,369
  • 1
  • 25
  • 55