Platform: Way to map unique id for addOne

Created on 7 Mar 2018  路  3Comments  路  Source: ngrx/platform

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ x] Feature request
[ ] Documentation issue or request

What is the current behavior?

Currently from what I understand one has to explicitly add id property for addOne to not add the object as undefined entity.

Expected behavior:

There should be a way to say trackBy UserId

Similar issue was raised in stackoverflow question: https://stackoverflow.com/questions/48995046/ngrx-entity-ids-are-undefined-in-the-state

Most helpful comment

@MikeRyanDev sorry, actually I had edited the issue and you may have received the earlier version while replying.

Say I have a model where there's no id property but a property like UserId how do I tell ngrx to identify entities by UserId and not id property.

All 3 comments

You probably wouldn't want to generate IDs in your reducers because that would break the purity of your reducer. That is, if we automatically generated an ID for your entities you would no longer have a guarantee that calling adapter.addOne(...) produced the same result for each call. This would make testing reducer functions harder because then you would have to mock out the adapter.

Ideally, you should generate an ID for your entities in your effects.

@MikeRyanDev sorry, actually I had edited the issue and you may have received the earlier version while replying.

Say I have a model where there's no id property but a property like UserId how do I tell ngrx to identify entities by UserId and not id property.

@shyamal890

export const userAdapter: EntityAdapter<User> = createEntityAdapter<User>({
    selectId: (user: User) => user.userId
});

If by property you mean a JS Object (since you wrote UserId as a type in capital), this will not work, an id (just as in any database) needs to be a primitive

Was this page helpful?
0 / 5 - 0 ratings