如何与另一个查询共享缓存的阿波罗客户端数据 [英] How to share cached apollo-client data with another query

查看:238
本文介绍了如何与另一个查询共享缓存的阿波罗客户端数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将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(在<Home />中)和2. getProduct($id)(在<ProductDetail />中).在从<Home />开始然后单击产品的场景中,我希望<ProductDetail />组件在查询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.

  • Demo: https://shopify-storefront-example-rdfwtslzng.now.sh/
  • Source: 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?

这是两个查询的摘要:

1:" getProducts "(例如,在<Home />组件中使用)

1: "getProducts" (e.g. used in a <Home /> component)

query getProducts {
  shop {
    products(first: 20) {
      edges {
        node {
          id
          ... on Product {
            title
          }
        }
      }
    }
  }
}

2:" getProduct "(例如,在<ProductDetail />组件中使用)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆