Executing Mutations from React

Apollo Client's mutation APIs allow React components to trigger GraphQL mutations.

For example:

const CREATE_USER = gql`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      id
      name
    }
  }
`;

The component can call:

const [createUser, { loading, error }] = useMutation(CREATE_USER);

Then:

await createUser({
  variables: {
    input: {
      name,
      email
    }
  }
});

After a mutation, the client cache may need to be updated.

Suppose the application has:

query Users {
  users {
    id
    name
  }
}

Creating a user does not necessarily mean Apollo can infer how your specific UI should update every query. Depending on the schema and cache configuration, you may need to use cache updates, refetching, or mutation result normalization.

A good client architecture treats mutation completion and cache consistency as explicit concerns.

React Mutation
const CREATE_USER = gql`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      id
      name
      email
    }
  }
`;

function CreateUserForm() {
  const [createUser, { loading }] = useMutation(CREATE_USER);

  const submit = async () => {
    await createUser({
      variables: {
        input: {
          name: "Alice",
          email: "alice@example.com"
        }
      }
    });
  };

  return <button disabled={loading} onClick={submit}>Create</button>;
}
💡 The mutation hook returns a function used to execute the operation and state describing the mutation. After completion, the application may need to update or refetch related cached queries.
Key Takeaways
  • Mutations are triggered explicitly by application actions.
  • Mutation variables are supplied separately.
  • Mutation completion may require cache updates.
  • Loading and error states should be represented in the UI.
Knowledge Check

Why might a React application need to update the Apollo cache after a successful mutation?