1
1
import type { ImmerHook } from './useImmer' ;
2
2
3
- import { freeze , produce } from 'immer' ;
3
+ import { freeze } from 'immer' ;
4
4
5
- import { useForceUpdate } from './useForceUpdate ' ;
5
+ import { useImmer } from './useImmer ' ;
6
6
import { useUnmount } from './useUnmount' ;
7
7
8
8
export function createGlobalState < S > ( ) : ( ) => ImmerHook < S | undefined > ;
@@ -11,31 +11,25 @@ export function createGlobalState<S>(initialValue?: S): () => ImmerHook<S | unde
11
11
const store = {
12
12
state : freeze ( typeof initialValue === 'function' ? initialValue ( ) : initialValue , true ) ,
13
13
setState ( updater : any ) {
14
- const prev = store . state ;
15
- if ( typeof updater === 'function' ) {
16
- store . state = produce ( store . state , updater ) ;
17
- } else {
18
- store . state = freeze ( updater ) ;
19
- }
20
- if ( ! Object . is ( store . state , prev ) ) {
21
- for ( const update of store . updates ) {
22
- update ( ) ;
23
- }
14
+ for ( const update of store . updates ) {
15
+ update ( updater ) ;
24
16
}
25
17
} ,
26
- updates : new Set < ( ) => void > ( ) ,
18
+ updates : new Set < ( ... args : any [ ] ) => any > ( ) ,
27
19
} ;
28
20
29
21
return ( ) => {
30
- const forceUpdate = useForceUpdate ( ) ;
31
- if ( ! store . updates . has ( forceUpdate ) ) {
32
- store . updates . add ( forceUpdate ) ;
22
+ const [ state , setState ] = useImmer ( store . state ) ;
23
+ store . state = state ;
24
+
25
+ if ( ! store . updates . has ( setState ) ) {
26
+ store . updates . add ( setState ) ;
33
27
}
34
28
35
29
useUnmount ( ( ) => {
36
- store . updates . delete ( forceUpdate ) ;
30
+ store . updates . delete ( setState ) ;
37
31
} ) ;
38
32
39
- return [ store . state , store . setState ] ;
33
+ return [ state , store . setState ] ;
40
34
} ;
41
35
}
0 commit comments