javascriptreactjscachinggraphqlapollo

Apollo GraphQL merge cached data


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
 }
}`

Next component

<MovieActors movieId={queryParamsId}/>

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

For each of these queries I use apollo hook

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

Everything is fine, but I got a warning message:

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: { ... }

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?


Solution

  • Solved!

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