I have a mutation called deleteHighlightedVerse
that simply deletes a record. When the record is deleted I want to update all of the Chapters that contain that highlighted verse, I can find them by searching the cache for all of the chapters with the applicable bibleApiChapterId
. Note that there can be multiple chapters that need to be updated, not just one. The code below is working fine except for the optimistic response.
When it comes to the optimistic response, I know what the issue is, but I don’t know why it’s happening or how to fix it. The update function is called twice, first when the optimistic response comes back (instantly) and then again when the actual result comes back. The issue is that first time the update function gets called the cache.data.data
object only has a few keys in it (2 to be exact), but when the real result comes back it has over 1500 keys. Obviously if I don’t have access to the full cache for optimistic update, then I’m not able to search for the chapters that I need to update. Is someone able to tell me why the cache.data.data
object does not contain the full cache for the optimistic response?
const [deleteHighlightedVerse] = useMutation(useDeleteHighlightedVerseMutation.mutation, {
variables: {
highlightedVerseId,
},
update: (cache, { data: { deleteHighlightedVerse } }) => {
// Find the chapters in the cache that need to be updated. Note that this is a little more complicated
// since there are potentially multiple chapters in the cache that need to be updated (same bibleApiChapterId)
// This console log prints `2` for the optimistic response update and then a much larger number for the actual response
console.log(_.keys(cache.data.data).length)
const chaptersCacheKeys = _.keys(cache.data.data).reduce((acc, cacheKey) => {
if (
cacheKey.startsWith('Chapter:') &&
cache.data.data[cacheKey]?.bibleApiChapterId === chapter.bibleApiChapterId
) {
return [...acc, cacheKey]
}
return acc
}, [])
chaptersCacheKeys.forEach((cacheKey) => {
cache.modify({
id: cacheKey,
fields: {
highlightedVerses(existingHighlightedVerseRefs = [], { readField }) {
return existingHighlightedVerseRefs.filter(
(highlightedVerseRef) =>
deleteHighlightedVerse.id !== readField('id', highlightedVerseRef)
)
},
},
})
})
},
optimisticResponse: {
deleteHighlightedVerse: {
__typename: 'HighlightedVerse',
id: highlightedVerseId,
},
},
onCompleted,
onError,
})