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

查看:213
本文介绍了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钩子

For each of these queries I use apollo hook

const {数据,正在加载,错误} = useQuery(GET_DATA,{变量:{id:queryParamsId}}))

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

一切都很好,但是我收到了警告消息:

Everything is fine, but I got a warning message:

替换查询对象的影片字段时,缓存数据可能会丢失. 要解决此问题(这不是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天全站免登陆