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.
36 lines
928 B
36 lines
928 B
import { createStore } from 'jotai'
|
|
import React, { useContext, createContext } from 'react'
|
|
|
|
export type Store = ReturnType<typeof createStore>
|
|
|
|
export const InternalPageContext = createContext<Store | undefined>(
|
|
undefined,
|
|
)
|
|
|
|
export const useInternalStore = (): Store => {
|
|
const store = useContext(InternalPageContext)
|
|
if (!store) {
|
|
throw new Error(
|
|
`Unable to find internal Page store, Did you wrap the component within PageStoreProvider?`,
|
|
)
|
|
}
|
|
return store
|
|
}
|
|
|
|
export const usePageStoreOptions = () => ({
|
|
store: useInternalStore(),
|
|
})
|
|
|
|
export const pageStore = createStore()
|
|
|
|
export const PageStoreProvider = ({ children }: React.PropsWithChildren) => {
|
|
const internalStoreRef = React.useRef<Store>()
|
|
|
|
if (!internalStoreRef.current) {
|
|
internalStoreRef.current = pageStore
|
|
}
|
|
|
|
return React.createElement(InternalPageContext.Provider, {
|
|
value: internalStoreRef.current
|
|
}, children)
|
|
}
|