forked from react-hookz/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
47 lines (46 loc) · 1.92 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
import {type DependencyList, useEffect} from 'react';
import {type ConditionsList, type ConditionsPredicate} from '../types.js';
import {truthyAndArrayPredicate} from '../util/const.js';
import {type EffectCallback, type EffectHook} from '../util/misc.js';
/**
* Like `useEffect` but its callback is invoked only if all given conditions match a given predicate.
*
* @param callback Function that will be passed to the underlying effect hook.
* @param deps Dependency list like the one passed to `useEffect`. If not
* `undefined`, the effect will be triggered when the dependencies change and the given `conditions`
* satisfy the `predicate`.
* @param conditions List of conditions.
* @param predicate Predicate that should be satisfied by every condition in `conditions`. By
* default, the predicate checks that every condition in `conditions` is truthy.
* @param effectHook Effect hook that will be used to run `callback`. Must match the type signature
* of `useEffect`, meaning that the `callback` should be placed as the first argument and the
* dependency list as second.
* @param effectHookRestArgs Extra arguments that are passed to the `effectHook` after the
* `callback` and the dependency list.
*/
// eslint-disable-next-line max-params
export function useConditionalEffect<
Cond extends ConditionsList,
Callback extends EffectCallback = EffectCallback,
Deps extends DependencyList | undefined = DependencyList | undefined,
HookRestArgs extends any[] = any[],
R extends HookRestArgs = HookRestArgs,
>(
callback: Callback,
deps: Deps,
conditions: Cond,
predicate: ConditionsPredicate<Cond> = truthyAndArrayPredicate,
effectHook: EffectHook<Callback, Deps, HookRestArgs> = useEffect,
...effectHookRestArgs: R
): void {
effectHook(
(() => {
if (predicate(conditions)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return callback();
}
}) as Callback,
deps,
...effectHookRestArgs,
);
}