UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

49 lines (48 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCounter = void 0; var react_1 = require("react"); var __1 = require(".."); var resolveHookState_1 = require("../util/resolveHookState"); /** * Tracks a numeric value. * * @param initialValue The initial value of the counter. * @param max The maximum value the counter is allowed to reach. * If `initialValue` is greater than `max`, then `max` is set as the initial value. * @param min The minimum value the counter is allowed to reach. * If `initialValue` is smaller than `min`, then `min` is set as the initial value. */ function useCounter(initialValue, max, min) { if (initialValue === void 0) { initialValue = 0; } var _a = (0, __1.useMediatedState)(initialValue, function (v) { if (typeof max !== 'undefined') { v = Math.min(max, v); } if (typeof min !== 'undefined') { v = Math.max(min, v); } return v; }), state = _a[0], setState = _a[1]; var stateRef = (0, __1.useSyncedRef)(state); return [ state, (0, react_1.useMemo)(function () { return ({ get: function () { return stateRef.current; }, set: setState, dec: function (delta) { if (delta === void 0) { delta = 1; } setState(function (val) { return val - (0, resolveHookState_1.resolveHookState)(delta, val); }); }, inc: function (delta) { if (delta === void 0) { delta = 1; } setState(function (val) { return val + (0, resolveHookState_1.resolveHookState)(delta, val); }); }, reset: function (val) { if (val === void 0) { val = initialValue; } setState(function (v) { return (0, resolveHookState_1.resolveHookState)(val, v); }); }, }); }, [initialValue, setState, stateRef]), ]; } exports.useCounter = useCounter;