@@ -11,17 +11,18 @@ export const startTransition: (scope: TransitionFunction) => void =
11
11
12
12
/**
13
13
* An implementation of state with dependency-tracking.
14
+ * @param initialState - The initial state object.
14
15
*/
15
- export const useStateWithDeps = < S = any > (
16
- state : any
16
+ export const useStateWithDeps = < S = Record < string , any > > (
17
+ initialState : S
17
18
) : [
18
- MutableRefObject < any > ,
19
+ MutableRefObject < S > ,
19
20
Record < keyof S , boolean > ,
20
21
( payload : Partial < S > ) => void
21
22
] => {
22
23
const [ , rerender ] = useState < Record < string , unknown > > ( { } )
23
24
const unmountedRef = useRef ( false )
24
- const stateRef = useRef ( state )
25
+ const stateRef = useRef < S > ( initialState )
25
26
26
27
// If a state property (data, error, or isValidating) is accessed by the render
27
28
// function, we mark the property as a dependency so if it is updated again
@@ -31,9 +32,10 @@ export const useStateWithDeps = <S = any>(
31
32
data : false ,
32
33
error : false ,
33
34
isValidating : false
34
- } as any )
35
+ } as Record < keyof S , boolean > )
35
36
36
37
/**
38
+ * Updates state and triggers re-render if necessary.
37
39
* @param payload To change stateRef, pass the values explicitly to setState:
38
40
* @example
39
41
* ```js
@@ -54,18 +56,21 @@ export const useStateWithDeps = <S = any>(
54
56
let shouldRerender = false
55
57
56
58
const currentState = stateRef . current
57
- for ( const _ in payload ) {
58
- const k = _ as keyof S
59
+ for ( const key in payload ) {
60
+ if ( Object . prototype . hasOwnProperty . call ( payload , key ) ) {
61
+ const k = key as keyof S
59
62
60
- // If the property has changed, update the state and mark rerender as
61
- // needed.
62
- if ( currentState [ k ] !== payload [ k ] ) {
63
- currentState [ k ] = payload [ k ]
63
+ // If the property has changed, update the state and mark rerender as
64
+ // needed.
65
+ if ( currentState [ k ] !== payload [ k ] ) {
66
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
67
+ currentState [ k ] = payload [ k ] !
64
68
65
- // If the property is accessed by the component, a rerender should be
66
- // triggered.
67
- if ( stateDependenciesRef . current [ k ] ) {
68
- shouldRerender = true
69
+ // If the property is accessed by the component, a rerender should be
70
+ // triggered.
71
+ if ( stateDependenciesRef . current [ k ] ) {
72
+ shouldRerender = true
73
+ }
69
74
}
70
75
}
71
76
}
0 commit comments