Skip to content

Commit e96b533

Browse files
Update useSession to pause before SSR hydration completes
1 parent e29e0ef commit e96b533

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

packages/react/src/auth/useSession.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type {
77
LimitToKnownKeys,
88
Select,
99
} from "@gadgetinc/api-client-core";
10+
import { useEffect, useState } from "react";
1011
import { useApi } from "../GadgetProvider.js";
1112
import { useGet } from "../useGet.js";
1213
import type { OptionsType, ReadOperationOptions } from "../utils.js";
@@ -61,6 +62,11 @@ export function useSession<
6162
const fallbackApi = useApi();
6263
const api = client ?? (fallbackApi as ClientType);
6364

65+
const [hydrated, setHydrated] = useState(false);
66+
useEffect(() => {
67+
setHydrated(true);
68+
}, []);
69+
6470
if (api && "currentSession" in api && "session" in api) {
6571
const { select: selection, ...restOptions } = options ?? ({} as any);
6672
const { user: userSelect, ...sessionSelect } = selection ?? { user: undefined };
@@ -69,6 +75,7 @@ export function useSession<
6975

7076
const opts: any = {
7177
suspense: true,
78+
pause: !hydrated,
7279
select: {
7380
...sessionSelection,
7481
...(userSelection && { user: userSelection }),
@@ -79,7 +86,7 @@ export function useSession<
7986
const [{ data: session, error }] = useGet(api.currentSession, opts);
8087

8188
if (error) throw error;
82-
if (!session) throw new Error("currentSession not found but should be present");
89+
if (!session && !opts?.pause && hydrated) throw new Error("currentSession not found but should be present");
8390
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
8491
return typeof client == "undefined" ? session : (session as any);
8592
} else {

0 commit comments

Comments
 (0)