From 9a391cc052446c70b5dfd5c6a846bff2ddfc35fc Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Mon, 2 May 2022 18:24:02 +0200 Subject: [PATCH] docs: cache updates, fix #1186 --- .../docs/src/guide-components/mutation.md | 39 +++++++---- .../docs/src/guide-composable/mutation.md | 64 +++++++++++++------ packages/docs/src/guide-option/mutations.md | 10 ++- 3 files changed, 76 insertions(+), 37 deletions(-) diff --git a/packages/docs/src/guide-components/mutation.md b/packages/docs/src/guide-components/mutation.md index 59886ae..2cf47d9 100644 --- a/packages/docs/src/guide-components/mutation.md +++ b/packages/docs/src/guide-components/mutation.md @@ -106,9 +106,18 @@ export default { }, } // Read the query from cache - const data = store.readQuery(query) - // Mutate cache result - data.thread.messages.push(sendMessageToThread.message) + let data = store.readQuery(query) + // Change cache result + data = { + ...data, + thread: { + ...data.thread, + messages: [ + ...data.thread.messages, + sendMessageToThread.message + ], + }, + } // Write back to the cache store.writeQuery({ ...query, @@ -191,18 +200,20 @@ export default { }, } // Read the query from cache - const data = store.readQuery(query) - // Look for the deleted item - const index = data.thread.messages.findIndex(m => m.id === this.messageId) - if (index !== -1) { - // Mutate cache result - data.thread.messages.splice(index, 1) - // Write back to the cache - store.writeQuery({ - ...query, - data, - }) + let data = store.readQuery(query) + // Change cache result + data = { + ...data, + thread: { + ...data.thread, + messages: data.thread.messages.filter(m => m.id !== this.messageId), + }, } + // Write back to the cache + store.writeQuery({ + ...query, + data, + }) }, } } diff --git a/packages/docs/src/guide-composable/mutation.md b/packages/docs/src/guide-composable/mutation.md index 99b62d6..7d56c34 100644 --- a/packages/docs/src/guide-composable/mutation.md +++ b/packages/docs/src/guide-composable/mutation.md @@ -307,11 +307,11 @@ In this example, if we already loaded the list of messages containing the one wi If a mutation modifies multiple entities, or if it creates or deletes one or many entities, the Apollo Client will *not* automatically update the cache to reflect the changes made by the mutation. Instead, you should update the cache using an `update` function in the options. -The purpose of this `update` function is to modify your cached data to match the changes made by the mutation on the server. +The purpose of this `update` function is to modify your cached data to match the changes made by the mutation on the server. Note that Apollo cache data is immutable so you need to either use the `...` (spread) operator or deeply clone the cached data before modifying it. For example, our `sendMessage` mutation should add the new message to our cache: -```vue{33-37} +```vue{33-43}