angularngrx

How to stop sorting by id when @ngrx EntityAdapter


Here is my adapter:

const adapter: EntityAdapter<SampleModel> = createEntityAdapter<SampleModel>();

and here is the reducer:

adapter.addMany(action.payload.samples, {
                ...initialSamplesState,
                totalCount: action.payload.totalCount,
                listLoading: false,
                lastQuery: action.payload.page,
                showInitWaitingMessage: false
            });

My model has an id field and the adapter is sorting the HTTP response array by id automatically. I would like to know how I can stop it.


Solution

  • You can't, it's JavaScript that does this.

    You can sort entities with the sortComparer method on the adapter.

    export function sortByName(a: User, b: User): number {
      return a.name.localeCompare(b.name);
    }
    
    export const adapter: EntityAdapter<User> = createEntityAdapter<User>({
      sortComparer: sortByName,
    });
    

    See the docs for more info.