@aiszlab/relax 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { type Dispatch, type SetStateAction } from 'react';
|
|
2
2
|
import { type State } from '../utils/is-state-getter';
|
|
3
|
+
interface Props<T> {
|
|
4
|
+
defaultState?: State<T>;
|
|
5
|
+
}
|
|
3
6
|
/**
|
|
4
7
|
* @author murukal
|
|
5
8
|
*
|
|
6
9
|
* @description
|
|
7
10
|
* controlled state
|
|
8
11
|
*/
|
|
9
|
-
export declare const useControlledState: <T>(controlledState: State<T>) => [T, Dispatch<SetStateAction<T>>];
|
|
12
|
+
export declare const useControlledState: <T>(controlledState: State<T>, { defaultState }?: Props<T>) => [T, Dispatch<SetStateAction<T>>];
|
|
13
|
+
export {};
|
|
@@ -8,11 +8,21 @@ import { isUndefined } from '../utils/is-undefined.js';
|
|
|
8
8
|
* @description
|
|
9
9
|
* controlled state
|
|
10
10
|
*/
|
|
11
|
-
const useControlledState = (controlledState) => {
|
|
11
|
+
const useControlledState = (controlledState, { defaultState } = {}) => {
|
|
12
12
|
/// initialize state
|
|
13
13
|
const [state, setState] = useState(() => {
|
|
14
|
+
// state function, run it for value
|
|
14
15
|
if (isStateGetter(controlledState))
|
|
15
16
|
return controlledState();
|
|
17
|
+
// not controlled use default prop
|
|
18
|
+
if (isUndefined(controlledState)) {
|
|
19
|
+
if (isUndefined(defaultState))
|
|
20
|
+
return controlledState;
|
|
21
|
+
if (isStateGetter(defaultState))
|
|
22
|
+
return defaultState();
|
|
23
|
+
return defaultState;
|
|
24
|
+
}
|
|
25
|
+
// default use controlled state
|
|
16
26
|
return controlledState;
|
|
17
27
|
});
|
|
18
28
|
useEffect(() => {
|
|
@@ -25,7 +35,7 @@ const useControlledState = (controlledState) => {
|
|
|
25
35
|
// if state is equal with value
|
|
26
36
|
if (controlledState === state)
|
|
27
37
|
return;
|
|
28
|
-
|
|
38
|
+
// update inner state
|
|
29
39
|
setState(controlledState);
|
|
30
40
|
}, [controlledState]);
|
|
31
41
|
return [state, setState];
|