59 lines
1.3 KiB
TypeScript
59 lines
1.3 KiB
TypeScript
|
|
/**
|
||
|
|
* useWizard Hook
|
||
|
|
*
|
||
|
|
* Primary hook for accessing wizard context.
|
||
|
|
* Provides all wizard functionality to step components.
|
||
|
|
*/
|
||
|
|
|
||
|
|
import { useContext } from 'react';
|
||
|
|
import { WizardContext } from './WizardProvider';
|
||
|
|
import type { WizardContextValue } from './types';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Hook to access wizard context
|
||
|
|
*
|
||
|
|
* @throws Error if used outside of WizardProvider
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* ```tsx
|
||
|
|
* function MyStepComponent() {
|
||
|
|
* const {
|
||
|
|
* data,
|
||
|
|
* updateField,
|
||
|
|
* next,
|
||
|
|
* prev,
|
||
|
|
* errors,
|
||
|
|
* isValidating,
|
||
|
|
* } = useWizard<MyFormData>();
|
||
|
|
*
|
||
|
|
* return (
|
||
|
|
* <form>
|
||
|
|
* <input
|
||
|
|
* value={data.name || ''}
|
||
|
|
* onChange={(e) => updateField('name', e.target.value)}
|
||
|
|
* />
|
||
|
|
* {errors.name && <span>{errors.name}</span>}
|
||
|
|
* <button onClick={prev}>Back</button>
|
||
|
|
* <button onClick={next} disabled={isValidating}>
|
||
|
|
* {isValidating ? 'Validating...' : 'Next'}
|
||
|
|
* </button>
|
||
|
|
* </form>
|
||
|
|
* );
|
||
|
|
* }
|
||
|
|
* ```
|
||
|
|
*/
|
||
|
|
export function useWizard<
|
||
|
|
TData extends Record<string, unknown> = Record<string, unknown>
|
||
|
|
>(): WizardContextValue<TData> {
|
||
|
|
const context = useContext(WizardContext);
|
||
|
|
|
||
|
|
if (!context) {
|
||
|
|
throw new Error(
|
||
|
|
'useWizard must be used within a WizardProvider. ' +
|
||
|
|
'Wrap your component tree with <WizardProvider>.'
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
return context as WizardContextValue<TData>;
|
||
|
|
}
|