问题描述
我正在使用apollo-client@2.3.x(&react-apollo@2.1.x)和标准InMemoryCache,通过其GraphQl Storefront API查询Shopify商店.
我有两个查询:1.getProducts(在<Home />中)和2. getProduct($id)(in <ProductDetail />).在场景中,从<Home />开始,然后单击产品,我希望<ProductDetail />组件在查询2运行之前显示查询1的缓存响应.
- demo:
- 来源:/_src
您可以在演示中看到,单击产品时,data是控制台中的一个空
有人可以在这里启发我,(a)为什么它不起作用,以及(b)我该怎么做?
这是两个查询的摘要:
1:" getProducts "(例如,在<Home />组件中使用)
query getProducts { shop { products(first: 20) { edges { node { id ... on Product { title } } } } } }
2:" getproduct "(例如,在<ProductDetail />组件中使用)
query getProduct($id: ID!) { node(id: $id) { ... on Product { title } } }
推荐答案
GraphQL客户端也无法对解析器的实现做出假设,即使对于人类,API似乎遵循一个简单的模式,查询的行为似乎很容易.您需要使用 cache redirect .
好吧,我在这里为您尝试过.我真的没有使用这些中继API,但应该与示例相似.
cacheRedirects: { Query: { getProduct: (_, args, { getCacheKey }) => ({ __typename: 'Node', node: getCacheKey({ __typename: 'Product', id: args.id }), }), }, },
问题描述
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 } } }
推荐答案
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 }), }), }, },