Cache update field alias

I have a query fragment with one of its fields defined multiple times using graphql alias, example:

fragment cartData on cart {
  id
  deleted_cart_items: cart_items(
    where: {
      _or: [
        { deleted: { _eq: true } }
      ]
    }
    limit: 50
    order_by: { updated_at: desc }
  ) {
    ...cartItemData
  }
  cart_items(
    where: { deleted: { _eq: false } }
    limit: 50
    order_by: { updated_at: desc }
  ) {
    ...cartItemData
  }
}

When using apollo client and trying to update my cache after a mutation, i cannot figure out how to access the alias field deleted_cart_items . the cache update seems to only see cart_items (in fact it goes into the cart_items() field method twice and totally ignores the deleted_cart_items() update field)

question is, how do I tell the cache update mechanism to treat this alias as a separate field (b/c I have different logic that needs to be applied to it)

Hi! Any aliases defined in your query are ignored by the cache, as you’ve already noticed. Each root query’s cache key is built from a combination of the field name and the JSON stringified variables. If you reference the field name in a cache.modify call, the modifier function will be called once for each permutation of variables in the cache, which explains why your modifier function gets called twice. That way, you can decide for each permutation of variables how that particular cache object is supposed to be updated.

The problem is how to know which set of variables is currently being handled in the modifier function. Unfortunately, all you have to work with is cache.modify's storeFieldName helper, which contains the cache key (which in turn, as I said before, is a combination of the field name and the JSON stringified variables). You can try to extract the variables from that, which is rather inconvenient.

I’m covering this very issue in my caching guide. You’ll find a bunch of concrete examples there on how to solve it.

1 Like

Thank you @mindnektar, I will go through your guide and try to figure it out.