hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { type Accessor, type ParentProps, createContext, createMemo, useContext } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { getSchool } from "@/api/school"; |
| 4 | import { useAuth } from "@/stores/auth-context"; |
| 5 | |
| 6 | type SchoolContextValue = { |
| 7 | /** The session school's display name; null while logged out, loading, or failed. */ |
| 8 | name: Accessor<string | null>; |
| 9 | }; |
| 10 | |
| 11 | const SchoolContext = createContext<SchoolContextValue>(); |
| 12 | |
| 13 | export 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 | |
| 34 | const NO_SCHOOL: SchoolContextValue = { name: () => null }; |
| 35 | |
| 36 | /** Outside a provider (isolated component tests) there is simply no name to show. */ |
| 37 | export function useSchool(): SchoolContextValue { |
| 38 | return useContext(SchoolContext) ?? NO_SCHOOL; |
| 39 | } |