ngrx-entity-relationship
ngrx-entity-relationship copied to clipboard
ngrxEntityRelationshipReducer with @ngrx/data has unexpected behavior
Problem
The ngrxEntityRelationshipReducer meta reducer does not work as expected when used along with @ngrx/data.
Here is a stackblitz project to illustrate the behavior: stackblitz
For these examples say the backend returns that:
{
"id": "1",
"firstName": "John",
"lastName": "Smith",
"companyId": "1",
"company": {
"id": "1",
"name": "Magic",
"adminId": "2",
"addressId": "1",
"address": {
"id": "1",
"street": "Main st.",
"city": "Town",
"country": "Land"
}
}
}
ngrxEntityRelationshipReducer does update the other entity collections, but since @ngrx/data has already added the response from the server to the entity cache, the entity in the cache still contains the related entities that were in the server response.
So if we dispatch reduceGraph after @ngrx/data loads this user, the entities in entityCache will look like that:
User
{
"id": "1",
"firstName": "John",
"lastName": "Smith",
"companyId": "1",
"company": {
"id": "1",
"name": "Magic",
"adminId": "2",
"addressId": "1",
"address": {
"id": "1",
"street": "Main st.",
"city": "Town",
"country": "Land"
}
}
}
Company
{
"id": "1",
"name": "Magic",
"adminId": "2",
"addressId": "1"
}
Address
{
"id": "1",
"street": "Main st.",
"city": "Town",
"country": "Land"
}
Worth Mentioning
Something to note, @ngrx/data does not automatically initialize the entityCache with empty collections. It starts like that:
{
entityCache: { }
}
So if we tell @ngrx/data to load a user entity then dispatch reduceGraph on the response, the store will look something like that:
{
entityCache: {
User: { ... }
}
}
The simplest way I found to deal with this is to just add empty arrays into all the entity collections when the app initializes. You can also see this in the stackblitz example.