GraphQL query responding with old data

I have a mutation set up to update a document.
I have a query in place on the same document.

What is currently happening:

  1. Fire off the mutation.
  2. Changes are reflected on Atlas.
  3. Receive response from the mutation.
  4. Query returns with expired data.

Why does the query come in with expired data after I’ve sent a mutation?
I’m 80% sure this was not happening a month ago. Did something change?
My UI updates based on the query signal, so every time I save a document, the UI is updating to the expired data, which is not consistent with the DB.

Hello @Ryan_Goodwin,

Thank you for raising your concern.

Could you please confirm my understanding of your issue-

  1. You updated the document via a graphQL mutation
  2. The updated data is visible on Atlas
  3. You run a graphQL query on the same data
  4. You received old data than the new one you updated to?

If my understanding is correct, it’s possible the query is returning cached data. Could you let us know how are you running the mutation/query? Are you using a client like Apollo?

I look forward to your response.

Cheers, :performing_arts:
Henna

1 Like

Yes, I edit the document via a GQL mutation. I’m using @apollo/client.
I then see the correct update on Atlas.

My UI awaits the return of the update mutation.

Then, when the query fires again, it returns with old data (the state of the document just before the update mutation was run).

If I then reload the page, thereby triggering the query again, the correct data is returned.

Caching seems a reasonable cause to look into.

Caching was definitely part of the problem.

The key to my solution ended up being here in the apollo docs.

In case it’s helpful for someone in the future, this is basically my code. I had to add a refetchQueries key when passing options to the mutation. Refer to the apollo docs for configuration details. I found it to be a little confusing figuring out how to reference the query that you want to be reloaded.

const UpdateDocumentMutation = gql`
  mutation UpdateDocument(
    $documentId: String!,
    $updates: DocumentUpdateInput!
  ){
    updatedDocument: updateOneDocument(query: { _id: $documentId }, set: $updates) {
      _id
    }
  }
`;

function useUpdateDocument(document) {
  const [updateDocumentMutation] = useMutation(UpdateDocumentMutation);

  const updateDocument = async (document) => {
    const { updatedDocument } = await updateDocumentMutation({
      variables: {
        recipeId: document._id,
        updates: document.updates
      },
      refetchQueries: [
        'Document'
      ]
    });
    return updatedDocument;
  };

  return updateDocument;
}
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.