Map query result to another query's cache
See original GitHub issueI’m using Apollo to build a production React Native app and I’m super grateful for all the great work you guys have done. Kudos!
There are a couple of things that I think could improve and I know many of them are already in the works (e.g., reimplementing loading
logic in react-apollo
and restructuring the design around fragments in apollo-client
). It’s super annoying that loading
can be undefined sometimes and it’s impossible to work with fragments so I’m looking forward to those changes!
There is another improvement that I wanted to mention because I’m not sure if it is in the works and I would love apollo-client
to have something like it.
Imagine you have the following 2 queries:
query ($userId: ID!) {
user(id: $userId) {
name
email
posts {
edges {
node {
title
createdAt
}
}
}
}
}
query ($postId: ID!) {
post(id: $postId) {
title
createdAt
}
}
If the second query returns a post that would’ve been included in the users’s post from the first query, there should be no network request. Currently with apollo-client
, because they’re different queries, the cache doesn’t know any better.
I propose that we add an option to ApolloClient
, similar to dataIdFromObject
, called queryIdFromObject
(this name is probably a bad one) that will let you map the result of a query to another query’s key in the internal Redux store, with the purpose of improving the cache.
Here’s how the option would be used for the example above:
const client = new ApolloClient({
queryIdFromObject: ({ __typename, id }) => `$ROOT_QUERY.${__typename}:${id}`,
});
Potentially, this option could only be allowed for the root query (I don’t see it being beneficial elsewhere) and dataIdFromObject
could be used internally so that the code above could be simplified to:
const client = new ApolloClient({
// maybe this name is better?
rootQueryNameFromObject: ({ __typename }) => singularize(__typename.toLowerCase()),
});
Regardless, this would greatly reduce the number of trips to the API that the app needs to make.
Thoughts?
EDIT: If the server is Relay compatible, then it would be even simpler because the relevant root query would be node
and/or nodes
Issue Analytics
- State:
- Created 7 years ago
- Comments:13 (6 by maintainers)
Top GitHub Comments
Hoping to get this done and documented before the end of the week! Things have been very busy around here because of the GraphQL Summit.
This is now implemented! #809 Just some tests to do.