Why are mutations cached?

Hi, I’ve noticed that mutations are saved in the Apollo Client Cache.
If I trigger identical mutations, that are in the cache, the client will always make a request to the server.

What is the purpose of having the mutations in the cache?
When will the Client use that cached mutations?

Example, updating the name-property of a Node.
Result in cache:

ROOT_MUTATION {
    __typename:"Mutation"
    updateNode({"id":"5faa648356cddc5844515e68","name":"New name"}):{
		__ref: "Node:5faa648356cddc5844515e68"
	}
}

Hello, good question!

Mutations are assumed to modify back-end data and therefore always make a server request. This is important because two “identical” mutations might, for example, create two distinct instances of an object as opposed to hard-setting values on a single object.

It’s true that the client might rarely need to make use of this cached updateNode field, but your queries (which can use the cache to avoid a network request) might make a great deal of use of the normalized cache object Node:5faa648356cddc5844515e68 that was presumably created or modified by the mutation.

This useful Node object is the value of the updateNode field in the server’s response, and the principle of least astonishment suggests that Apollo Client should cache every key and value included in an operation response, instead of selectively omitting data that might be helpful less often.

“Mutations are assumed to modify back-end data and therefore always make a server request.”
Yes, and any other behaviour would be strange and irrational.

“the principle of least astonishment suggests that Apollo Client should cache every key and value included in an operation response”
That should answer my questions, the cache does this “by design” and the ROOT_MUTATION are usually not used.

Thank you @StephenBarlow !

1 Like

Update for Apollo Client 3.4, as described in the changelog:

To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4 automatically clears any ROOT_MUTATION fields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing the keepRootFields: true option to client.mutate . ROOT_MUTATION result data are also passed to the mutation update function, so we recommend obtaining the results that way, rather than using keepRootFields: true , if possible.

So now, there is a special case for the ROOT_MUTATION object!

2 Likes