apollo-feature-requests icon indicating copy to clipboard operation
apollo-feature-requests copied to clipboard

Simplify API for nested cache.modify calls

Open lorensr opened this issue 5 years ago • 1 comments

Currently, modifying a non-root, non-normalized field requires nesting calls to cache.modify(), like the below code modifying ROOT_QUERY.currentUser.favoriteReviews:

const [removeReview] = useMutation(REMOVE_REVIEW_MUTATION, {
  update: (cache) => {
    cache.modify({
      fields: {
        currentUser(currentUserRef) {
          cache.modify({
            id: currentUserRef.__ref,
            fields: {
              favoriteReviews(reviews, { readField }) {
                return reviews.filter(review => readField('id', review) !== id)
              },
            },
          })
          // Keep Query.currentUser unchanged.
          return currentUserRef
        },
      },
    })
  },
})

It would be nice if there were a simpler API, for example allowing dot notation in fields:

const [removeReview] = useMutation(REMOVE_REVIEW_MUTATION, {
  update: (cache) => {
    cache.modify({
      fields: {
        'currentUser.favoriteReviews': (reviews, { readField }) =>
          reviews.filter((review) => readField('id', review) !== id),
      },
    })
  },
})

lorensr avatar Oct 16 '20 02:10 lorensr

@lorensr I like this idea, but I think I would prefer allowing nested fields, which should be unambiguous because objects and functions are easily distinguishable:

const [removeReview] = useMutation(REMOVE_REVIEW_MUTATION, {
  update(cache) {
    cache.modify({
      fields: {
        currentUser: {
          favoriteReviews: (reviews, { readField }) =>
            reviews.filter((review) => readField('id', review) !== id),
        },
      },
    })
  },
})

benjamn avatar Nov 11 '20 15:11 benjamn