Apollo GraphQL 合并缓存数据 [英] Apollo GraphQL merge cached data

查看:30
本文介绍了Apollo GraphQL 合并缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 2 个组件组成的页面,每个组件都有自己的数据请求例如

I have a page that consists of 2 components and each of them has its own request for data for example

<MovieInfo movieId={queryParamsId}/>

const GET_MOVIE_INFO = `gql
  query($id: String!){
   movie(id: $id){
    name
    description
 }
}`

下一个组件

<MovieActors movieId={queryParamsId}/>

const GET_MOVIE_ACTORS = `gql
  query($id: String!){
   movie(id: $id){
    actors
 }
}`

对于这些查询中的每一个,我都使用 apollo hook

For each of these queries I use apollo hook

const { data, loading, error } = useQuery(GET_DATA, {variable: {id: queryParamsId}}))

const { data, loading, error } = useQuery(GET_DATA, {variable: {id: queryParamsId}}))

一切正常,但我收到一条警告消息:

Everything is fine, but I got a warning message:

替换Query对象的movie字段时缓存数据可能会丢失.为了解决这个问题(这不是 Apollo Client 中的错误),要么确保所有 Movie 类型的对象都有 ID,要么为 Query.movi​​e 字段定义一个自定义合并函数,以便 InMemoryCache 可以安全地合并这些对象:{ ...}

Cache data may be lost when replacing the movie field of a Query object. To address this problem (which is not a bug in Apollo Client), either ensure all objects of type Movie have IDs, or define a custom merge function for the Query.movie field, so InMemoryCache can safely merge these objects: { ... }

谷歌浏览器可以正常工作,但此错误会影响 Safari 浏览器.一切都在粉碎.我 100% 确定这是因为此警告消息.在第一个请求中,我在缓存中设置了电影数据,在对同一查询的第二个请求中,我只是用新数据替换了旧数据,因此以前的缓存数据未定义.我该如何解决这个问题?

It's works ok with google chrome, but this error affects Safari browser. Everything is crushing. I'm 100% sure it's because of this warning message. On the first request, I set Movie data in the cache, on the second request to the same query I just replace old data with new, so previous cached data is undefined. How can I resolve this problem?

推荐答案

已解决!

 cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          YOUR_FIELD: {
            merge(existing = [], incoming: any) {
              return { ...existing, ...incoming };
              // this part of code is depends what you actually need to do, in my 
              case i had to save my incoming data as single object in cache
            }
          }
        }
      }
    }
  })
});

这篇关于Apollo GraphQL 合并缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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