Using Apollo graphQL has been great, once learning the caching functionality

I started writing because I had an issue, but I have resolved it and wanted to mention how much graphQL has helped simplify my code base.

There are many fields that I update independently (e.g. onBlur) to make the user experience fluid. I’ve found that I can create one query with all the needed fields to change, then only pass in the variables I want to actually update.

This is key, in that Apollo with update the cache correctly for those independently changing values. When I click on different items, I don’t need to worry about updating that cache manually (which is possible, but more complicated). For cache-updating to work correctly, the fields you return in the mutation must match the fields in your query.

Here’s an example:

const GET_ITEM = gql`
  query GetItem($id: ID) {
    item(id: $id) {
      id
      description
      criteria
    }
  }
`;

const UPDATE_ITEM = gql`
  mutation UpdateItem($id: ID, $description: String, $criteria: String) {
    itemUpdate(data: {
      id: $id
      description: $description
      criteria: $criteria
    }) {
      id
      description
      criteria
    }
  }
`;

The code to handle mutations is very straightforward after using an event that listens to field changes:

  const [updateItem] = useMutation(UPDATE_ITEM);

  const handleFieldChange = (key: string, value: string) => {
    updateItem({
      variables: {
        id: itemId,
        [key]: value,
      }
    });
  };