如何与另一个查询共享缓存的阿波罗客户端数据 [英] How to share cached apollo-client data with another query
问题描述
我正在使用 apollo-client@2.3.x
(& react-apollo@2.1.x
) 和标准的 InMemoryCache
>,通过他们的 GraphQL Storefront API 查询 Shopify 商店.
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.
我有两个查询:1. getProducts
(在
中)和 2. getProduct($id)
(在
中).在场景开始于
,然后点击一个产品,我希望
组件显示来自在查询 2 运行之前查询 1.
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.
- 演示:https://shopify-storefront-example-rdfwtslzng.now.sh/
- 来源:https://shopify-storefront-example-rdfwtslzng.now.sh/_src
您可以在演示中看到,当点击产品时,data
在控制台中是一个空的 {}
,直到第二次网络请求完成.我假设它会被缓存,因为查询共享相同的 __typename
,并使用节点"结构.
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.
有人可以在这里启发我吗,(A) 为什么它不起作用,以及 (B) 我怎样才能使它起作用?
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"(例如在
组件中使用)
1: "getProducts" (e.g. used in a <Home />
component)
query getProducts {
shop {
products(first: 20) {
edges {
node {
id
... on Product {
title
}
}
}
}
}
}
2:getProduct"(例如在
组件中使用)
2: "getProduct" (e.g. used in a <ProductDetail />
component)
query getProduct($id: ID!) {
node(id: $id) {
... on Product {
title
}
}
}
推荐答案
GraphQL 客户端无法对解析器的实现做出假设,即使对于人类来说 API 似乎遵循一个简单的模式并且查询的行为似乎微不足道.你需要帮助一下 缓存重定向.
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.
好的,我在这里为你试过了.我并不真正使用这些 Relay API,但它的工作方式应该与示例非常相似.
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 }),
}),
},
},
这篇关于如何与另一个查询共享缓存的阿波罗客户端数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!