0
votes

React + Apollo client app. I'm trying to read from my cache using readQuery but can't read the cached fields.

Here's a rundown:

Component SinglePost invokes useQuery which executes my GET_POST query and caches the result. GET_POST query returns type Post!. All is fine, dev tools show that ROOT_QUERY contains a field called getPost with that post.

const { loading, data } = useQuery(GET_POST, {
    variables: {
      postID,
    }
});

SinglePost has a child component DeleteButton that deletes a comment on click. It invokes useMutation and deletes a comment. DELETE_COMMENT query returns type Comment!.

const [deleteComment] = useMutation(DELETE_COMMENT, {
    variables: {
      postID,
      commentID,
    },
});

Post has an array of comments, and now I need to update its array in the cache and remove the deleted comment. I use update function within the deleteComment mutation to get the cache object and use readQuery to get the getPost field from it, but it returns null, even though it's there in the dev tools.

update(cache, result) {
  const cacheData = cache.readQuery({
    query: GET_POST,
  });
  // code that doesn't run because cacheData is null
}

I suspect when mutating posts via mutations that return a Post type it successfully reads the getPost field, but when mutation queries return a Comment type it can't read getPost in its mutation hook... because there's no reference to a Post type?

For now I'm using refetchQueries as a workaround. I don't like making extra calls to the server, but my smooth brain just can't figure this out. Any help is appreciated.

1
you must pass the same variable (postID)xadm
You're right!!! I forgot the variables. Thanks!minefield_tester

1 Answers

0
votes

Whoops, no variables were ever passed to the query.

update(cache, result) {
  const cacheData = cache.readQuery({
    query: GET_POST,
    variables: {
      postID
    }
  });
}