usehooks-ts
Version:
React hook library, ready to use, written in Typescript.
40 lines • 1.48 kB
JavaScript
import { useCallback, useMemo, useState } from 'react';
function useStep(maxStep) {
var _a = useState(1), currentStep = _a[0], setCurrentStep = _a[1];
var canGoToNextStep = useMemo(function () { return currentStep + 1 <= maxStep; }, [currentStep, maxStep]);
var canGoToPrevStep = useMemo(function () { return currentStep - 1 >= 1; }, [currentStep]);
var setStep = useCallback(function (step) {
var newStep = step instanceof Function ? step(currentStep) : step;
if (newStep >= 1 && newStep <= maxStep) {
setCurrentStep(newStep);
return;
}
throw new Error('Step not valid');
}, [maxStep, currentStep]);
var goToNextStep = useCallback(function () {
if (canGoToNextStep) {
setCurrentStep(function (step) { return step + 1; });
}
}, [canGoToNextStep]);
var goToPrevStep = useCallback(function () {
if (canGoToPrevStep) {
setCurrentStep(function (step) { return step - 1; });
}
}, [canGoToPrevStep]);
var reset = useCallback(function () {
setCurrentStep(1);
}, []);
return [
currentStep,
{
goToNextStep: goToNextStep,
goToPrevStep: goToPrevStep,
canGoToNextStep: canGoToNextStep,
canGoToPrevStep: canGoToPrevStep,
setStep: setStep,
reset: reset,
},
];
}
export default useStep;
//# sourceMappingURL=useStep.js.map