apollographql / apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
Other
130 stars 7 forks source link

Simplify API for nested cache.modify calls #266

Open lorensr opened 3 years ago

lorensr commented 3 years ago

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),
      },
    })
  },
})
benjamn commented 3 years ago

@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),
        },
      },
    })
  },
})