Skip to main content

apolloClient-mutation

How to write a mutation with optimistic update and actual cache update:

Writing a Mutation with Optimistic Update and Cache Update

  1. Define the Mutation with Optimistic Response:

    • Create the mutation with an optimisticResponse to immediately update the UI with predicted results.
    updateOrgClient({
    variables: { updateRequest: { id: client.id, payload: newClient } },
    optimisticResponse: {
    __typename: 'Mutation',
    updateOrgClient: {
    ...newClient,
    id: client.id,
    },
    },
    update(cache, { data }) {
    if (data?.updateOrgClient) {
    cache.modify({
    fields: {
    getOrgClient(existingData = {}) {
    return {
    ...existingData,
    ...data.updateOrgClient,
    };
    },
    },
    });
    }
    },
    });
  2. Cache Update:

    • Use the update function to modify the cache after the mutation completes.
    update(cache, { data }) {
    if (data?.updateOrgClient) {
    cache.modify({
    fields: {
    getOrgClient(existingData = {}) {
    return {
    ...existingData,
    ...data.updateOrgClient,
    };
    },
    },
    });
    }
    }
  3. Adding a New Client with Optimistic Response:

    • Handle adding a new client similarly, generating a temporary ID.
    addClient({
    variables: { client: newClient },
    optimisticResponse: {
    __typename: 'Mutation',
    addClient: {
    ...newClient,
    id: Math.random().toString(36).substring(2, 15), // Generate a temporary ID
    },
    },
    update(cache, { data }) {
    if (data?.addClient) {
    cache.modify({
    fields: {
    getClients(existingClients = []) {
    return [...existingClients, data.addClient];
    },
    },
    });
    }
    },
    });

By following these steps, you can implement mutations with optimistic updates and actual cache updates effectively.

References for optimistic update can be found here