Apollo-feature-requests: Simplify API for nested cache.modify calls

Created on 16 Oct 2020  路  1Comment  路  Source: apollographql/apollo-feature-requests

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

Most helpful comment

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

>All comments

@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),
        },
      },
    })
  },
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hwillson picture hwillson  路  8Comments

jbachhardie picture jbachhardie  路  3Comments

Vincz picture Vincz  路  3Comments

noaelad picture noaelad  路  3Comments

jkdowdle picture jkdowdle  路  3Comments