Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ intended change without catching real bugs.
profile page (`app/routes/`): the whole page is rendered with mocked API
responses, for example searching, the suggestions when a search has no
results, errors from the API, and browsing from one book to the next.
- **Hook tests** for `useBookSearchParams`, `usePageParam`, `useCountUp` and
`useDataIsDelayed`.
- **Hook tests** for `useBookSearchParams`, `usePageParam`, `useCountUp`,
`useDataIsDelayed` and `useLogOut`.
- **Snapshot test** for `BookCard`. The rendered HTML is stored in
`__snapshots__/` next to the test and compared on every run. If a markup
change is intended, update the snapshot with `pnpm test -u`.
Expand Down
7 changes: 3 additions & 4 deletions frontend/app/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { authClient } from "~/api/auth";
import { MobileHeaderMenu } from "~/components/MobileHeaderMenu/MobileHeaderMenu";
import { Button, buttonVariants } from "~/components/ui/Button";
import { DarkModeToggle } from "~/components/ui/DarkModeToggle";
import { useLogOut } from "~/hooks/useLogOut";
import { cn } from "~/lib/utils";

function Header() {
const { data: session, isPending } = authClient.useSession();
const logOut = useLogOut();

return (
<header className="flex items-center justify-between border-b-2 border-zinc-800 not-dark:bg-white px-10 py-3.75">
Expand Down Expand Up @@ -52,10 +54,7 @@ function Header() {
<Button
variant="outline"
onClick={() => {
void (async () => {
await authClient.signOut();
location.reload();
})();
void logOut();
}}
>
Log out
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "lucide-react";
import { Link } from "react-router";
import { authClient } from "~/api/auth";
import { useLogOut } from "~/hooks/useLogOut";
import { Button } from "~/components/ui/Button";
import { DarkModeToggle } from "~/components/ui/DarkModeToggle";
import {
Expand All @@ -23,6 +24,7 @@ import {

function MobileHeaderMenu() {
const { data: session, isPending } = authClient.useSession();
const logOut = useLogOut();

return (
<DropdownMenu>
Expand Down Expand Up @@ -67,10 +69,7 @@ function MobileHeaderMenu() {
<DropdownMenuItem
variant="destructive"
onClick={() => {
void (async () => {
await authClient.signOut();
location.reload();
})();
void logOut();
}}
>
<LogOutIcon />
Expand Down
58 changes: 58 additions & 0 deletions frontend/app/hooks/useLogOut.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { ApolloClient, ApolloLink, InMemoryCache } from "@apollo/client";
import { ApolloProvider } from "@apollo/client/react";
import { FAVORITE_BOOK_IDS } from "~/hooks/useFavoriteBooks";
import { useLogOut } from "~/hooks/useLogOut";

// The order of the steps matters, so each one adds its name to this list
const steps = vi.hoisted((): string[] => []);

vi.mock("~/api/auth", () => ({
authClient: {
signOut: vi.fn(() => {
steps.push("signOut");
return Promise.resolve();
}),
},
}));

afterEach(() => {
steps.length = 0;
vi.unstubAllGlobals();
});

describe("useLogOut", () => {
it("signs out, clears the user's data from the cache and reloads the page", async () => {
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});
// Data that belongs to the logged-in user
client.writeQuery({
query: FAVORITE_BOOK_IDS,
data: { favoriteBookIds: [1, 2, 3] },
});
expect(client.readQuery({ query: FAVORITE_BOOK_IDS })).toEqual({
favoriteBookIds: [1, 2, 3],
});

client.onClearStore(() => {
steps.push("clearStore");
return Promise.resolve();
});
// jsdom can't reload the page. Nothing else in this test reads the location
vi.stubGlobal("location", { reload: () => steps.push("reload") });

const { result } = renderHook(() => useLogOut(), {
wrapper: ({ children }: { children: ReactNode }) => (
<ApolloProvider client={client}>{children}</ApolloProvider>
),
});
await result.current();

expect(steps).toEqual(["signOut", "clearStore", "reload"]);
expect(client.readQuery({ query: FAVORITE_BOOK_IDS })).toBeNull();
});
});
25 changes: 25 additions & 0 deletions frontend/app/hooks/useLogOut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useApolloClient } from "@apollo/client/react";
import { authClient } from "~/api/auth";

/**
* Returns a function that logs the user out.
*
* Apollo Client's cache can hold data that belongs to the user, such as their
* favorites and reviews, so we clear it when they log out. Reloading the page
* afterwards also empties the cache, since it only lives in memory, and resets
* all other state in the app. We still clear it explicitly, so this doesn't
* depend on the reload.
*/
function useLogOut() {
const client = useApolloClient();

return async function logOut() {
await authClient.signOut();
// clearStore() only empties the cache. resetStore() would also fetch the
// active queries again, which is wasted right before a reload
await client.clearStore();
location.reload();
};
}

export { useLogOut };
7 changes: 3 additions & 4 deletions frontend/app/routes/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from "~/components/ui/Card";
import { Skeleton } from "~/components/ui/Skeleton";
import { REVIEW_PAGE_PARAM, useMyReviews } from "~/hooks/useReviews";
import { useLogOut } from "~/hooks/useLogOut";
import { FAVORITE_BOOKS_PAGE_LIMIT } from "~/lib/constants";
import { Separator } from "~/components/ui/Separator";

Expand All @@ -28,6 +29,7 @@ export function meta() {

export default function ProfilePage() {
const { data: session, isPending } = authClient.useSession();
const logOut = useLogOut();
const { page, isInvalid: isInvalidPage, firstPageSearch } = usePageParam();

const { books, totalCount, topGenres, loading, error } = useFavoriteBooks({
Expand Down Expand Up @@ -149,10 +151,7 @@ export default function ProfilePage() {
variant="outline"
className="w-full border-destructive/50 text-destructive"
onClick={() => {
void (async () => {
await authClient.signOut();
location.reload();
})();
void logOut();
}}
>
Log out
Expand Down