Apollo-client: non-global dataIdFromObject?

Created on 24 Sep 2016  路  5Comments  路  Source: apollographql/apollo-client

When I write an implementation for dataIdFromObject, it seems like if I have two entities with the same ID that they'll end up at the same place in the store. Is there a way to implement a non-global dataIdFromObject function? Or alternatively have access to the path for the data so that that can be considered when assigning an ID?

Most helpful comment

dataIdFromObject is specifically to tell apollo client that two objets with different paths are actually the same. If you don't want that, you can just not assign it an id, in which case apollo client will use the path.

All 5 comments

dataIdFromObject is specifically to tell apollo client that two objets with different paths are actually the same. If you don't want that, you can just not assign it an id, in which case apollo client will use the path.

@helfer I understand that, but the problem arises when you have two entities that have the same ID, but are different.

For example, if I make a query for a user with ID 1:

user(id: 1) {
  id
  name
}

And then make a query for a message with ID 1:

message(id: 1) { 
  id
  from
  to
}

The dataIdFromObject isn't able to distinguish between these two, which are separate entities, but with the same ID.

I still want to be able to normalize all of this into an entity mapped structure, but the problem is that I can't determine that message and user are different.

@kesne ah, I see. In that case you want to make sure to include __typename and use a combination of __typename and id for the globally unique id by providing the dataIdFromObject argument to the ApolloClient constructor: dataIdFromObject: obj => obj.__typename + obj.id or something like that.

@helfer That's pretty unfortunate. It seems less than ideal to require adding __typename to every query to get entity mapping working. It seems like this situation would be a common one based on how most people store their data?

@kesne Right now you can use queryTransformer for that, but we have an open PR that changes it to addTypename, and it will be true by default, so you won't have to add __typename to every query.

See the API docs: http://dev.apollodata.com/core/apollo-client-api.html

Was this page helpful?
0 / 5 - 0 ratings