Does Apollo auto-update the cache if a mutation changes a nested subfield?

Viewed 54

If I have a mutation returning something like:

{
  _id
  subField {
    subField2: ["valueChanged"] 
  }
}

The previous value of subField2 was an empty Array, and the mutation adds a value to that Array, should I expect Apollo to automatically change the cache?

And if subField2 is not an Array but a String, a mutation that changes this String should update the cache Automatically?

1 Answers

Editing is the easiest case because you don't need to do anything for the list to auto update after you edit the Item. Apollo Cache, by default, uses the pair __typename + id (or _id) as a primary key to every cache object.

Where as in case of adding an item, it's a bit different because when we get our response from the server (the newly created Item) Apollo doesn't "know" that the list should be updated with the new item (and, sometime, it shouldn't). For this we have to programatically add our new item to the list, and one of the parameters of the useMutation hook is the update function, that is there specifically for that purpose.

const ADD_ITEM = gql`
  mutation($item: ItemInput) {
    addItem(item: $item) {
      id
      title
      price
    }
  }
`;

const AddItem = () => {
  const [addItem, { loading }] = useMutation(ADD_ITEM);

  return (
    <ItemForm
      disabled={loading}
      onSubmit={item => {
        addItem({
          variables: {
            item
          },
          update: (cache, { data: { addItem } }) => {
            const data = cache.readQuery({ query: GET_ITEMS });
            data.items = [...data.items, addItem];
            cache.writeQuery({ query: GET_ITEMS }, data);
          }
        });
      }}
    />
  );
};

More details here

Related