Created
June 22, 2023 04:43
-
-
Save bingomanatee/680a4c9ccfcef83742a036f63080319c to your computer and use it in GitHub Desktop.
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 { useEffect, useMemo, useState } from 'react' | |
import { Forest } from '@wonderlandlabs/forest' | |
import { leafConfig, leafI } from '@wonderlandlabs/forest/lib/types' | |
type configArray = [initializer: (...args: any) => leafConfig, ...rest: any]; | |
export default function useForest<valueType>( | |
config: leafConfig | configArray, | |
onCreate?: (leaf: leafI) => unknown | |
) | |
: [value: valueType, state: leafI] { | |
// --- state is created here ---- | |
const state = useMemo(() => { | |
let initializer = config; | |
if (Array.isArray(config)) { | |
initializer = config[0](...config.slice(1)) | |
} | |
return new Forest(initializer); | |
}, []); | |
const [value, setValue] = useState<valueType>(state.value); | |
// -- and two things happen here: | |
// (1) the state output is subscribed to | |
// (2) the opttional passed-through functioon is called with the state to "initialize" it. | |
useEffect(() => { | |
const sub = state.subscribe(setValue); | |
let onComplete: unknown = null; | |
if (onCreate) { | |
// ---- for some bizarre reason this is getting called TWICE. | |
onComplete = onCreate(state); | |
} | |
return () => { | |
sub.unsubscribe() | |
if (typeof onComplete === 'function') { | |
onComplete(); | |
} | |
}; | |
}, [state]); | |
return [value, state]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment