9

Is it necessary to have ids in ngrx/entities that will not be changed? I want to use string property path as id. It is uniq. But it can be changed. Should I use uuid as ids in this case?

mr__brainwash
  • 1,334
  • 3
  • 16
  • 40

4 Answers4

25

You can pass in a function to override the default id selection when creating your adapter:

export const adapter: EntityAdapter<Model> = createEntityAdapter({
  selectId: (model: Model) => model.modelId,
});
Rakhat
  • 4,783
  • 4
  • 40
  • 50
bc1105
  • 1,270
  • 8
  • 8
  • 2
    This answer does not answer the question that is being asked. The question is asking how to update the id of an existing entity, not how to specify a custom id. – Shane Loveland Nov 05 '19 at 23:19
4

We needed to update the Ids in the EntityAdapter because the API returns the unique ID, for future references, which is not available when first adding it to the store. So you could change it yourself if you want to.

const updateSelectedRooms = new selectedRoomsActions.UpdateSelectedRooms(
            {
                entities: [
                    {
                        changes: {
                            id: mockResponse.data.rooms[0].roomId,
                            pricing: mockResponse.data.rooms[0].pricing,
                        },
                        id: '1234-5678',
                    },
                ],
            },
        );
rvdm
  • 213
  • 2
  • 9
0

As per the official documentation of Entity Adapter:

selectId: A method for selecting the primary id for the collection. Optional when the entity has a primary key of id

I think it will solve the problems related to Entity Id. You can also try Entity Adapter for any functionality you want to perform on an Entity out of the box, and to go a step forward, you should try @ngrx/data

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
0

NGRX introduced the mapOne function in the entityAdaptor. This can be used to update an entity with a different id, by passing the old id.

Define adaptor

const updatesAdapter: EntityAdapter<ModelEntity> = createEntityAdapter<ModelEntity>();

In the reducer

...
on(Action.someUpdateAction, (state,
                                 {newEntity, oldId}): State => {
    return updatesAdapter.mapOne({
      id: oldId,
      map: (e: ModelEntity) => ({
        ...newEntity 
      })
    }, state);
  }),
...
Steve Maris
  • 957
  • 9
  • 15