如何使用 Apollo Client 缓存嵌套对象?

问题描述 投票:0回答:2

我正在使用 Contentful GraphQL API 来获取项目集合,在此示例中为足球俱乐部。

query Clubs($limit: Int!, $skip: Int!) {
    clubCollection(limit: $limit, skip: $skip) {
        total
        items {
            name
            description
        }
    }
}

响应的结构是:

clubCollection: {
  items: [{
    ... array of all the clubs
  }]
}

看起来 Apollo

InMemoryCache
仅在其 ROOT_QUERY 对象中缓存完整查询。但不是每个单独的俱乐部。缓存的设置如下所示:

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        clubCollection: concatContentfulPagination()
      },
    },
  },
})

有谁知道我如何定位

items
中的俱乐部,以便我可以缓存每个单独的俱乐部?

编辑: 感谢@xadm的回答,我意识到我不需要像这样扩展

InMemoryCache

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        clubCollection: {
          items: { 
          
          },
          ...concatContentfulPagination()
        }
      },
    },
  },
})

而是根据对象的类型将其添加到 typePolicies 的根中,对我来说它是

Club
。当我补充说它确实有效时!

new InMemoryCache({
  typePolicies: {
    Club: {
      keyFields: ['name']
    },
    Query: {
      fields: {
        clubCollection: concatContentfulPagination()
      },
    },
  },
})
reactjs graphql apollo apollo-client contentful
2个回答
2
投票

项目应该有一个

id
请求的道具......进行规范化 - Apollo 正在规范缓存 GraphQL 客户端

需要正确缓存条目/类型/子类型。

https://graphql.org/learn/caching/

它,唯一密钥可以是

id
_id
或使用
typePolicies
- customizing-identifier- Generation-by-type 按类型自定义密钥。

https://www.apollographql.com/docs/react/caching/cache-configuration/#default-identifier- Generation

在这种情况下(项目内没有可查询的

id
属性),您应该检查 API(文档/规范/架构或探索网络响应正文 -
__typename
对象的
items
属性)俱乐部项目条目的类型(可能是
Club
)并自定义缓存策略,例如:

new InMemoryCache({
  typePolicies: {
    Club: {
      keyFields: ['name']
    },

...假设

name
是唯一的。


0
投票

为此目的,您可以使用反应变量。这样您就可以在代码中的任何位置访问clubs数组,而无需重新运行查询并对其执行任何数组操作。 访问页面了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.