问题
I'm using apollo-client@2.3.x
(& react-apollo@2.1.x
), with the standard InMemoryCache
, to query a Shopify store via their GraphQL Storefront API.
I have two queries: 1. getProducts
(in <Home />
), and 2. getProduct($id)
(in <ProductDetail />
). In the scenario starts on <Home />
, then clicks on a product, I'd like the <ProductDetail />
component to show the cached response from query 1 before query 2 runs.
- Demo: https://shopify-storefront-example-rdfwtslzng.now.sh/
- Source: https://shopify-storefront-example-rdfwtslzng.now.sh/_src
You can see in the demo, when clicking on the product, that data
is an empty {}
in the console, until the second network request is complete. I assumed that it would be cached, as the queries share the same __typename
, and use the "node" structure.
Can someone enlighten me here, (A) why it doesn't work, and (B) how can I make it so?
Here's a summary of the two queries:
1: "getProducts" (e.g. used in a <Home />
component)
query getProducts {
shop {
products(first: 20) {
edges {
node {
id
... on Product {
title
}
}
}
}
}
}
2: "getProduct" (e.g. used in a <ProductDetail />
component)
query getProduct($id: ID!) {
node(id: $id) {
... on Product {
title
}
}
}
回答1:
The GraphQL client cannot make assumptions about the implementations of the resolvers even when for a human the API seem to follow an easy pattern and the behaviour of the queries seems trivial. You need to help out a bit with a Cache Redirect.
Okay, I tried this here for you. I don't really work with these Relay APIs but it should be working quite similarly to the example.
cacheRedirects: {
Query: {
getProduct: (_, args, { getCacheKey }) => ({
__typename: 'Node',
node: getCacheKey({ __typename: 'Product', id: args.id }),
}),
},
},
来源:https://stackoverflow.com/questions/50827274/how-to-share-cached-apollo-client-data-with-another-query