Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ngrxEntityRelationshipReducer with @ngrx/data has unexpected behavior #1603

Open
duxnp opened this issue Jul 21, 2022 · 0 comments
Open

ngrxEntityRelationshipReducer with @ngrx/data has unexpected behavior #1603

duxnp opened this issue Jul 21, 2022 · 0 comments

Comments

@duxnp
Copy link

duxnp commented Jul 21, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant