context.tsx 641 B

1234567891011121314151617181920212223242526
  1. import { ParentProps, Show, createContext, useContext } from "solid-js"
  2. export function createInitializedContext<
  3. Name extends string,
  4. T extends { ready: boolean },
  5. >(name: Name, cb: () => T) {
  6. const ctx = createContext<T>()
  7. return {
  8. use: () => {
  9. const context = useContext(ctx)
  10. if (!context) throw new Error(`No ${name} context`)
  11. return context
  12. },
  13. provider: (props: ParentProps) => {
  14. const value = cb()
  15. return (
  16. <Show when={value.ready}>
  17. <ctx.Provider value={value} {...props}>
  18. {props.children}
  19. </ctx.Provider>
  20. </Show>
  21. )
  22. },
  23. }
  24. }