11import * as React from 'react'
2+ import { get } from 'lodash'
23
34import {
45 Ayanami ,
@@ -7,11 +8,19 @@ import {
78 ScopeConfig ,
89 ActionMethodOfAyanami ,
910 ConstructorOf ,
11+ TransientScope ,
1012} from './core'
1113
1214export type HooksResult < M extends Ayanami < S > , S > = [ Readonly < S > , ActionMethodOfAyanami < M , S > ]
1315
14- export function useAyanamiInstance < M extends Ayanami < S > , S > ( ayanami : M ) : HooksResult < M , S > {
16+ interface UseAyanamiInstanceConfig {
17+ destroyWhenUnmount ?: boolean
18+ }
19+
20+ export function useAyanamiInstance < M extends Ayanami < S > , S > (
21+ ayanami : M ,
22+ config ?: UseAyanamiInstanceConfig ,
23+ ) : HooksResult < M , S > {
1524 const ikari = React . useMemo ( ( ) => combineWithIkari ( ayanami ) , [ ayanami ] )
1625 const [ state , setState ] = React . useState < S > ( ( ) => ayanami . getState ( ) )
1726
@@ -20,6 +29,17 @@ export function useAyanamiInstance<M extends Ayanami<S>, S>(ayanami: M): HooksRe
2029 return ( ) => subscription . unsubscribe ( )
2130 } , [ ] )
2231
32+ React . useEffect (
33+ ( ) => ( ) => {
34+ const isDestroyWhenUnmount = get ( config , 'destroyWhenUnmount' , false )
35+
36+ if ( isDestroyWhenUnmount ) {
37+ ayanami . destroy ( )
38+ }
39+ } ,
40+ [ ] ,
41+ )
42+
2343 return [ state , ikari . triggerActions ] as HooksResult < M , S >
2444}
2545
@@ -29,5 +49,10 @@ export function useAyanami<M extends Ayanami<S>, S>(
2949) : M extends Ayanami < infer SS > ? HooksResult < M , SS > : HooksResult < M , S > {
3050 const ayanami = React . useMemo ( ( ) => getInstanceWithScope ( A , config ) , [ A ] )
3151
32- return useAyanamiInstance < M , S > ( ayanami ) as any
52+ const useAyanamiInstanceConfig = React . useMemo ( ( ) : UseAyanamiInstanceConfig => {
53+ const scope = get ( config , 'scope' , false )
54+ return { destroyWhenUnmount : scope === TransientScope }
55+ } , [ ] )
56+
57+ return useAyanamiInstance < M , S > ( ayanami , useAyanamiInstanceConfig ) as any
3358}
0 commit comments