Search code examples
graphqlapolloapollo-clientreact-apollo

Can Apollo read partial fragments from cache?


I have a simple mutation editPerson. It changes the name and/or description of a person specified by an id.

I use this little snippet to call the mutator from React components:

function useEditPerson(variables) {
    const gqlClient = useGQLClient();
    const personFragment = gql`fragment useEditPerson__person on Person {
        id
        name
        description
    }`;

    return useMutation(gql`
        ${personFragment}

        mutation editPerson($id: ID!, $description: String, $name: String) {
            editPerson(id: $id, description: $description, name: $name) {
                ...useEditPerson__person
            }
        }
    `, {
        variables,
        optimisticResponse: vars => {
            const person = gqlClient.readFragment({
                id: vars.id,
                fragment: personFragment,
            });

            return {
                editPerson: {
                    __typename: "Person",
                    description: "",
                    name: "",
                    ...person,
                    ...vars,
                },
            };
        },
    });
}

This works well enough unless either the name or description for the indicated person hasn't yet been queried and does not exist in the cache; in this case person is null. This is expected from readFragment - any incomplete fragment does this.

The thing is I really need that data to avoid invariant errors - if they're not in the cache I'm totally okay using empty strings as default values, those values aren't displayed anywhere in the UI anyway.

Is there any way to read partial fragments from the cache? Is there a better way to get that data for the optimistic response?


Solution

  • I guess you use the snippet in the form that has all the data you need. So, you can pass the needed data to your useEditPerson hook through the arguments and then use in optimistic response, and then you won't need to use gqlClient.