-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.ts
53 lines (46 loc) · 1.62 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import {type DependencyList, type Dispatch, useCallback, useEffect, useState} from 'react';
import {useSyncedRef} from '../useSyncedRef/index.js';
import {type InitialState, type NextState} from '../util/resolve-hook-state.js';
export type ValidityState = {
isValid: boolean | undefined;
} & Record<any, any>;
export type ValidatorImmediate<V extends ValidityState = ValidityState> = () => V;
export type ValidatorDeferred<V extends ValidityState = ValidityState> = (
done: Dispatch<NextState<V>>
) => any;
export type Validator<V extends ValidityState = ValidityState> =
| ValidatorImmediate<V>
| ValidatorDeferred<V>;
export type UseValidatorReturn<V extends ValidityState> = [V, () => void];
/**
* Performs validation when any of provided dependencies has changed.
*
* @param validator Function that performs validation.
* @param deps Dependencies list that passed straight to underlying `useEffect`.
* @param initialValidity Initial validity state.
*/
export function useValidator<V extends ValidityState>(
validator: Validator<V>,
deps: DependencyList,
initialValidity: InitialState<V> = {isValid: undefined} as V,
): UseValidatorReturn<V> {
const [validity, setValidity] = useState(initialValidity);
const validatorRef = useSyncedRef(() => {
if (validator.length > 0) {
validator(setValidity);
} else {
setValidity((validator as ValidatorImmediate<V>)());
}
});
useEffect(() => {
validatorRef.current();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return [
validity,
useCallback(() => {
validatorRef.current();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
];
}