@react-hookz/web
Version:
React hooks done right, for browser and SSR.
47 lines (46 loc) • 2.13 kB
JavaScript
;
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConditionalEffect = void 0;
/* eslint-disable @typescript-eslint/no-explicit-any */
var react_1 = require("react");
var __1 = require("..");
/**
* Like `useEffect` but callback invoked only if conditions match predicate.
*
* @param callback Function that will be passed to underlying effect hook.
* @param deps Dependencies list like for `useEffect`. If not undefined - effect will be
* triggered when deps change AND conditions satisfy predicate.
* @param conditions Conditions array.
* @param predicate Predicate that defines whether conditions satisfying certain
* provision. By default, it is all-truthy provision, meaning that all
* conditions should be truthy.
* @param effectHook Effect hook that will be used to run callback. Must comply `useEffect`
* signature, meaning that callback should be placed as first argument and dependencies list
* as second.
* @param effectHookRestArgs Extra arguments that are passed to `effectHook`.
*/
function useConditionalEffect(callback, deps, conditions, predicate, effectHook) {
if (predicate === void 0) { predicate = __1.truthyAndArrayPredicate; }
if (effectHook === void 0) { effectHook = react_1.useEffect; }
var effectHookRestArgs = [];
for (var _i = 5; _i < arguments.length; _i++) {
effectHookRestArgs[_i - 5] = arguments[_i];
}
effectHook.apply(void 0, __spreadArray([(function () {
if (predicate(conditions)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return callback();
}
}),
deps], effectHookRestArgs, false));
}
exports.useConditionalEffect = useConditionalEffect;