forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

school-context.tsx39 lines, 1.3 KiBHistoryRawDownload
1import { type Accessor, type ParentProps, createContext, createMemo, useContext } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import { getSchool } from "@/api/school";
4import { useAuth } from "@/stores/auth-context";
5
6type SchoolContextValue = {
7 /** The session school's display name; null while logged out, loading, or failed. */
8 name: Accessor<string | null>;
9};
10
11const SchoolContext = createContext<SchoolContextValue>();
12
13export function SchoolProvider(props: ParentProps) {
14 const auth = useAuth();
15 // Keyed on the account id, so switching school (a new session) refetches.
16 // Seeded with null so no reader ever suspends the shell on it.
17 const userId = createMemo(() => auth.user()?.id ?? null);
18 const [school] = createResource(
19 userId,
20 async (id) => {
21 if (id === null) return null;
22 try {
23 return await getSchool();
24 } catch {
25 return null;
26 }
27 },
28 { initialValue: null },
29 );
30
31 return <SchoolContext.Provider value={{ name: () => school()?.name ?? null }}>{props.children}</SchoolContext.Provider>;
32}
33
34const NO_SCHOOL: SchoolContextValue = { name: () => null };
35
36/** Outside a provider (isolated component tests) there is simply no name to show. */
37export function useSchool(): SchoolContextValue {
38 return useContext(SchoolContext) ?? NO_SCHOOL;
39}