|
| 1 | +import * as React from 'react' |
| 2 | +import { get } from 'lodash' |
| 3 | + |
| 4 | +import { ActionMethodOfAyanami, Ayanami, combineWithIkari } from '../core' |
| 5 | + |
| 6 | +export interface UseAyanamiInstanceConfig { |
| 7 | + destroyWhenUnmount?: boolean |
| 8 | +} |
| 9 | + |
| 10 | +export type UseAyanamiInstanceResult<M extends Ayanami<S>, S> = [ |
| 11 | + Readonly<S>, |
| 12 | + ActionMethodOfAyanami<M, S> |
| 13 | +] |
| 14 | + |
| 15 | +type Config = UseAyanamiInstanceConfig |
| 16 | + |
| 17 | +type Result<M extends Ayanami<S>, S> = UseAyanamiInstanceResult<M, S> |
| 18 | + |
| 19 | +export function useAyanamiInstance<M extends Ayanami<S>, S>( |
| 20 | + ayanami: M, |
| 21 | + config?: Config, |
| 22 | +): Result<M, S> { |
| 23 | + const ayanamiRef = React.useRef(ayanami) |
| 24 | + const ikari = React.useMemo(() => combineWithIkari(ayanami), [ayanami]) |
| 25 | + const [state, setState] = React.useState<S>(() => ayanami.getState()) |
| 26 | + |
| 27 | + if (ayanamiRef.current !== ayanami) { |
| 28 | + ayanamiRef.current = ayanami |
| 29 | + setState(ayanami.getState()) |
| 30 | + } |
| 31 | + |
| 32 | + React.useEffect(() => { |
| 33 | + const subscription = ayanami.getState$().subscribe(setState) |
| 34 | + return () => subscription.unsubscribe() |
| 35 | + }, [ayanami]) |
| 36 | + |
| 37 | + React.useEffect( |
| 38 | + () => () => { |
| 39 | + const isDestroyWhenUnmount = get(config, 'destroyWhenUnmount', false) |
| 40 | + |
| 41 | + if (isDestroyWhenUnmount) { |
| 42 | + ayanami.destroy() |
| 43 | + } |
| 44 | + }, |
| 45 | + [ayanami, config], |
| 46 | + ) |
| 47 | + |
| 48 | + return [state, ikari.triggerActions] as Result<M, S> |
| 49 | +} |
0 commit comments