Get value from cache after mutation
Description
This example demonstrates how to use the Apollo Client to update the cache after a mutation. It shows how to read the current value from the cache, update it, and then write the new value back to the cache.
QueryRef(request) => valueChanges() => observable => subscribe => use it most of the time
When you do a mutation to update the cache:
you need to return the __typename (implicit) and id (explicit) of the object you are updating. ** If you forget the id
field, the cache will not be updated correctly ! **
Example
...
// service
private _getVersionSrv = inject(MediaGetVersionGQL);
// query ref return by the .watch() method
versionQueryRef = this._getVersionSrv.watch();
// observable to get the current value from the cache
versionChanged = this.versionQueryRef.valueChanges.pipe(
map(({ data }) => data.instance as unknown as MediaVersion),
);
// to signal
version = toSignal(this.versionChanged);
// example of usage in computed
assigns = computed(() => {
const version = this.version();
if (!version) {
return [];
}
return version.task.users
});
Now we want to update users
of the current task
of the current version
:
mutation MediaModifyTask($input: ModifyTaskInput!) {
modifyTask(input: $input) {
clientMutationId
task {
id // needed to update the cache
users {
id // needed to update the cache
display
picture
}
}
}
}
Now the request
const _o$ = this._modifyTaskSrv.mutate({
input: {
clientMutationId: version.task?.id,
users: users,
usersUpdateMode: relatedUsersUpdateMode,
},
});
await firstValueFrom(_o$);
With this setup the cache will be updated automatically after the mutation.
Improvments
Another improvement would be to use an Optimistic way to update the cache. This would ensure that the UI is updated immediately and with valid data, even if the request fails.