How to share cached apollo-client data with another query

北城以北 提交于 2019-12-08 11:56:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!