You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
928 B

5 months ago
  1. import { createStore } from 'jotai'
  2. import React, { useContext, createContext } from 'react'
  3. export type Store = ReturnType<typeof createStore>
  4. export const InternalPageContext = createContext<Store | undefined>(
  5. undefined,
  6. )
  7. export const useInternalStore = (): Store => {
  8. const store = useContext(InternalPageContext)
  9. if (!store) {
  10. throw new Error(
  11. `Unable to find internal Page store, Did you wrap the component within PageStoreProvider?`,
  12. )
  13. }
  14. return store
  15. }
  16. export const usePageStoreOptions = () => ({
  17. store: useInternalStore(),
  18. })
  19. export const pageStore = createStore()
  20. export const PageStoreProvider = ({ children }: React.PropsWithChildren) => {
  21. const internalStoreRef = React.useRef<Store>()
  22. if (!internalStoreRef.current) {
  23. internalStoreRef.current = pageStore
  24. }
  25. return React.createElement(InternalPageContext.Provider, {
  26. value: internalStoreRef.current
  27. }, children)
  28. }