Skip to content

Commit bddfe08

Browse files
committed
feat: add explicit SessionContext to tree
1 parent aad237c commit bddfe08

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import * as React from 'react';
2+
3+
import { UseSessionReturn } from '../hooks/useSession';
4+
5+
/** @internal */
6+
export const SessionContext = React.createContext<UseSessionReturn | undefined>(undefined);
7+
8+
/**
9+
* Ensures that a session is provided via context.
10+
* If no session is provided, an error is thrown.
11+
* @public
12+
*/
13+
export function useSessionContext() {
14+
const ctx = React.useContext(SessionContext);
15+
if (!ctx) {
16+
throw Error('tried to access session context outside of SessionProvider component');
17+
}
18+
return ctx;
19+
}
20+
21+
/**
22+
* Returns the session context if it exists, otherwise undefined.
23+
* @public
24+
*/
25+
export function useMaybeSessionContext() {
26+
return React.useContext(SessionContext);
27+
}
28+
29+
/**
30+
* Ensures that a session is provided, either via context or explicitly as a parameter.
31+
* If no session is provided, an error is thrown.
32+
* @public
33+
*/
34+
export function useEnsureSession(session?: UseSessionReturn) {
35+
const context = useMaybeSessionContext();
36+
const r = session ?? context;
37+
if (!r) {
38+
throw new Error(
39+
'No session provided, make sure you are inside a Session context or pass the session explicitly',
40+
);
41+
}
42+
return r;
43+
}

0 commit comments

Comments
 (0)