From 4cabfb90adbbc4a2d11d6ccb5bf5628c178f3d71 Mon Sep 17 00:00:00 2001 From: neopostmodern Date: Sat, 1 Apr 2023 23:37:04 +0200 Subject: [PATCH] fix(client): ensure proper cache-removal of deleted note --- client/src/renderer/hooks/useDeleteNote.tsx | 18 +++--------------- client/src/renderer/utils/cache.ts | 11 +++++++++++ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/client/src/renderer/hooks/useDeleteNote.tsx b/client/src/renderer/hooks/useDeleteNote.tsx index e3db702..c554578 100644 --- a/client/src/renderer/hooks/useDeleteNote.tsx +++ b/client/src/renderer/hooks/useDeleteNote.tsx @@ -2,12 +2,11 @@ import { gql, useMutation } from '@apollo/client'; import { useDispatch } from 'react-redux'; import { push } from 'redux-first-history'; import ErrorSnackbar from '../components/ErrorSnackbar'; -import { NOTES_QUERY } from '../containers/NotesPage/NotesPage'; import { - NotesForListQuery, ToggleDeletedNoteMutation, ToggleDeletedNoteMutationVariables, } from '../generated/graphql'; +import { removeNoteFromCache } from '../utils/cache'; const TOGGLE_DELETED_NOTE_MUTATION = gql` mutation ToggleDeletedNote($noteId: ID!) { @@ -33,22 +32,11 @@ const useDeleteNote = (note: { _id: string }) => { if (!data) { throw Error('[useDeletedLink.update] No data returned from mutation'); } - const cacheData = cache.readQuery({ - query: NOTES_QUERY, - }); - if (!cacheData) { - throw Error('[useDeletedLink.update] No data returned from cache'); - } - const { notes } = cacheData; if (!data.toggleDeletedNote.deletedAt) { throw Error("[useDeletedLink.update] Can't handle un-delete yet."); } - cache.writeQuery({ - query: NOTES_QUERY, - data: { - notes: notes.filter(({ _id }) => _id !== data.toggleDeletedNote._id), - }, - }); + + removeNoteFromCache(cache, data.toggleDeletedNote); }, }); diff --git a/client/src/renderer/utils/cache.ts b/client/src/renderer/utils/cache.ts index 25882d1..253723f 100644 --- a/client/src/renderer/utils/cache.ts +++ b/client/src/renderer/utils/cache.ts @@ -1,6 +1,17 @@ +import { ApolloCache } from '@apollo/client'; import apolloClient, { cachePersistor } from '../apollo'; export const clearApolloCache = () => { apolloClient.clearStore(); cachePersistor.purge(); }; + +export const removeNoteFromCache = ( + cache: ApolloCache, + note: { _id: string; __typename: string } +): void => { + const normalizedId = cache.identify(note); + cache.evict({ id: normalizedId }); + cache.gc(); // https://stackoverflow.com/questions/63192774/apollo-client-delete-item-from-cache#comment121727251_66713628 + return; +};