saleor-dashboard/src/hooks/useWizard.ts

62 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-03-31 17:56:53 +00:00
import { useState } from "react";
2020-04-03 14:29:32 +00:00
export interface UseWizardActions<T> {
2020-03-31 17:56:53 +00:00
next: () => void;
prev: () => void;
set: (step: T) => void;
}
2020-04-03 14:29:32 +00:00
export interface UseWizardOpts<T> {
onTransition: (prevStep: T, nextStep: T) => void;
}
export type UseWizard<T> = [T, UseWizardActions<T>];
function useWizard<T>(
initial: T,
steps: T[],
opts?: UseWizardOpts<T>
): UseWizard<T> {
2020-03-31 17:56:53 +00:00
const [stepIndex, setStepIndex] = useState(steps.indexOf(initial));
2020-04-03 14:29:32 +00:00
function goToStep(nextStepIndex) {
if (typeof opts?.onTransition === "function") {
opts.onTransition(steps[stepIndex], steps[nextStepIndex]);
}
setStepIndex(nextStepIndex);
}
2020-03-31 17:56:53 +00:00
function next() {
if (stepIndex === steps.length - 1) {
console.error("This is the last step");
} else {
2020-04-03 14:29:32 +00:00
goToStep(stepIndex + 1);
2020-03-31 17:56:53 +00:00
}
}
function prev() {
if (stepIndex === 0) {
console.error("This is the first step");
} else {
2020-04-03 14:29:32 +00:00
goToStep(stepIndex - 1);
2020-03-31 17:56:53 +00:00
}
}
function set(step: T) {
const newStepIndex = steps.findIndex(s => s === step);
if (newStepIndex === -1) {
console.error("Step does not exist");
} else {
2020-04-03 14:29:32 +00:00
goToStep(newStepIndex);
2020-03-31 17:56:53 +00:00
}
}
return [
steps[stepIndex],
{
next,
prev,
set
}
];
}
export default useWizard;