8000 Demonstrate cache deletion and garbage collection · nirus/fullstack-tutorial@e2e8d63 · GitHub
[go: up one dir, main page]

Skip to content

Commit e2e8d63

Browse files
committed
Demonstrate cache deletion and garbage collection
Remove all user details from the cache when logging out, using a combination of `cache.modify()` and `cache.gc()`.
1 parent 131949a commit e2e8d63

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

final/client/src/cache.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,3 @@ export const cache: InMemoryCache = new InMemoryCache({
3333
export const isLoggedInVar =
3434
cache.makeLocalVar<boolean>(!!localStorage.getItem('token'));
3535
export const cartItemsVar = cache.makeLocalVar<string[]>([]);
36-

final/client/src/containers/logout-button.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,38 @@
11
import React from 'react';
22
import styled from 'react-emotion';
3+
import { useApolloClient } from '@apollo/client';
34

45
import { menuItemClassName } from '../components/menu-item';
56
import { isLoggedInVar } from '../cache';
67
import { ReactComponent as ExitIcon } from '../assets/icons/exit.svg';
78

89
const LogoutButton = () => {
10+
const { cache } = useApolloClient();
911
return (
1012
<StyledButton
1113
data-testid="logout-button"
1214
onClick={() => {
15+
// Since we're logging out, remove all traces of the current user
16+
// from the cache. First use `cache.modify()` to remove the stored
17+
// `me` reference that was added to the cache by the `GET_MY_TRIPS`
18+
// query in `profile.tsx`. Then trigger garbage collection using
19+
// `cache.gc()` to remove the cached `User` object that is no longer
20+
// reachable.
21+
cache.modify(
22+
'ROOT_QUERY',
23+
{
24+
me(_, { DELETE }) {
25+
return DELETE;
26+
}
27+
}
28+
);
29+
cache.gc();
30+
31+
// Remove user details from localStorage.
1332
localStorage.clear();
33+
34+
// Let other parts of the application that are relying on logged in
35+
// state know we're now logged out.
1436
isLoggedInVar(false);
1537

1638
// TODO: This redirect is temporary. Eventually `makeLocalVar`

0 commit comments

Comments
 (0)
0