Skip to content

Commit

Permalink
fix(client): ensure proper cache-removal of deleted note
Browse files Browse the repository at this point in the history
  • Loading branch information
neopostmodern committed Apr 1, 2023
1 parent c68a6c0 commit 4cabfb9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
18 changes: 3 additions & 15 deletions client/src/renderer/hooks/useDeleteNote.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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!) {
Expand All @@ -33,22 +32,11 @@ const useDeleteNote = (note: { _id: string }) => {
if (!data) {
throw Error('[useDeletedLink.update] No data returned from mutation');
}
const cacheData = cache.readQuery<NotesForListQuery>({
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);
},
});

Expand Down
11 changes: 11 additions & 0 deletions client/src/renderer/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -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<any>,
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;
};

0 comments on commit 4cabfb9

Please sign in to comment.