summaryrefslogtreecommitdiffhomepage
path: root/cloud/web/src/util/context.tsx
blob: d1c6f4e7f7347d993729f462e1c00c5e153dea7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { ParentProps, Show, createContext, useContext } from "solid-js"

export function createInitializedContext<
  Name extends string,
  T extends { ready: boolean },
>(name: Name, cb: () => T) {
  const ctx = createContext<T>()

  return {
    use: () => {
      const context = useContext(ctx)
      if (!context) throw new Error(`No ${name} context`)
      return context
    },
    provider: (props: ParentProps) => {
      const value = cb()
      return (
        <Show when={value.ready}>
          <ctx.Provider value={value} {...props}>
            {props.children}
          </ctx.Provider>
        </Show>
      )
    },
  }
}