Last active
August 19, 2024 22:34
-
-
Save legraphista/95183a35a16f0bff9c3ccd1121199289 to your computer and use it in GitHub Desktop.
React MobX Context Builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useRef, useState} from 'react' | |
const resetSymbol = Symbol('reset'); | |
type ProviderChildren<Store extends new (...args: any[]) => InstanceType<Store>> = | |
| { children: React.ReactNode } | |
| { children: React.ReactNode, staticStore: InstanceType<Store> } | |
| { children: React.ReactNode, arguments: ConstructorParameters<Store> } | |
type Lifecycle<S extends new (...args: any[]) => InstanceType<S>> = { | |
init?: (instance: InstanceType<S>) => void | |
dispose?: (instance: InstanceType<S>) => void | |
} | |
export const createContext = <S extends new (...args: any[]) => InstanceType<S>>(Store: S, { | |
init, | |
dispose | |
}: Lifecycle<S> = {}) => { | |
const context = React.createContext<InstanceType<typeof Store> | null>(null); | |
const Provider = (props: ProviderChildren<S>): React.JSX.Element => { | |
const {children} = props; | |
const staticStore = 'staticStore' in props ? props.staticStore : null; | |
const args = 'arguments' in props ? props.arguments : []; | |
const firstArgsBypass = useRef(true); | |
const [store, setStore] = useState<InstanceType<S>>(staticStore || (() => new Store(...args))); | |
useEffect(() => { | |
init?.(store); | |
return () => dispose?.(store); | |
}, [store]); | |
useEffect(() => { | |
if(staticStore) return; | |
if(firstArgsBypass.current) { | |
firstArgsBypass.current = false; | |
return; | |
} | |
setStore(new Store(...args)); | |
}, args); | |
(store as any)[resetSymbol] = () => { | |
if (staticStore) throw new Error('Cannot reset static store'); | |
setStore(new Store(...args)); | |
} | |
return React.createElement(context.Provider, {value: store}, children); | |
} | |
const useStore = (): InstanceType<typeof Store> => { | |
const store = React.useContext(context); | |
if (!store) { | |
throw new Error(`No context found for ${Store.prototype.constructor.name}`); | |
} | |
return store; | |
} | |
return {Provider, useStore}; | |
} | |
export const resetStore = (store: any) => { | |
if (resetSymbol in store) { | |
store[resetSymbol](); | |
} else { | |
throw new Error('Store does not have reset method'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment