Why is it appended to every root query after adding the cache?

I’m apollo client 3 is using.

Adding a cache adds Post to all fields in the Root Query, regardless of type.
How can I update Root Query by distinguishing types?

{
 __typename:"Post"
 id:"443"
 status:"PRIVATE"
 category:"FAQ"
 type:"SERVICE"
 createdAt:"2022-05-12T07:48:49.000Z"
 service:"Artistscard"
 post_url:[]
 post_title:[]
}

 const [createFaq, {loading}] = useMutation<Result, Args>(CREATE_FAQ, {
    update(cache, {data}) {
      const createFaq = data?.createFaq;
      cache.modify({
        fields: {
          post(existingFaq = []) {
            const newFaqRef = cache.writeFragment({
              data: createFaq,
              fragment: FAQ_FRAGMENT,
            });
            return [newFaqRef, ...existingFaq];
          },
        },
      });
    },
  });
fragment FaqFragment on Post {
    id
    status
    category
    type
    createdAt
    service
    post_url {
      id
      url
      type_url
    }
    post_title {
      id
      title
      text
      language_code
      createdAt
      updatedAt
    }
  }
typePolicies: {
    Query: {
      fields: {
        post: {
          keyArgs: ['where', ['category', 'service', 'type']],
          read(existing, {args, toReference, canRead}) {
            if (args?.where.id) {
              const refs = [toReference({__typename: 'Post', id: args.where.id})];
              if (refs.find((ref) => !canRead(ref))) {
                return;
              }
              return refs;
            }
            return existing;
          },
        },
      },
    },
  },
1 Like

The problem is with the way you’re using cache.modify(). Unfortunately, cache.modify() does not support use cases where it needs to modify a field with arguments. There is a workaround here, but it is a bit complicated in my opinion. I would recommend trying to use writeQuery or writeFragment instead of modify if possible.

See more about this problem here: Have `cache.modify` functions receive `options.args` Β· Issue #7129 Β· apollographql/apollo-client Β· GitHub

1 Like