Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useRouter } from 'next/router';
- import React from 'react';
- import { RegisterFormStepOne, RegisterFormStepTwo } from '~/components/auth/register-form/steps';
- import { Alert, AlertDescription, AlertTitle } from '~/components/ui/Alert';
- import { type RegisterDto } from '~/config/form/auth/register-dto';
- import { api } from '~/utils/api';
- const TOTAL_STEPS = 2;
- const getMaxStep = (currentStep: number) => {
- return Math.min(currentStep + 1, TOTAL_STEPS - 1);
- };
- export const RegisterForm = () => {
- const router = useRouter();
- const [wasDataMutated, setWasDataMutated] = React.useState(false);
- const [data, setData] = React.useState<RegisterDto>({
- companyAddress: '',
- companyCity: '',
- companyEmail: '',
- companyName: '',
- companyPhone: '',
- companyPostalCode: '',
- email: '',
- firstName: '',
- gender: 'male',
- lastName: '',
- password: '',
- passwordConfirmation: '',
- });
- const registrationMutation = api.auth.register.useMutation();
- const currentStep = React.useMemo(() => {
- if (!wasDataMutated) {
- return 0;
- }
- if (router.query.step) {
- return getMaxStep(Number.parseInt(router.query.step as string, 10));
- }
- return 0;
- }, [router.query.step, wasDataMutated]);
- const onGoToNextStep = (stepData: Partial<RegisterDto>) => {
- setWasDataMutated(true);
- setData(oldData => ({
- ...oldData,
- ...stepData,
- }));
- };
- const onGoToPreviousStep: React.MouseEventHandler<HTMLButtonElement> = (event) => {
- event.preventDefault();
- void router.back();
- };
- React.useEffect(() => {
- if (!wasDataMutated) {
- const resetSteps = async () => await router.replace(router.pathname);
- void resetSteps();
- return;
- }
- const routePushOrSubmit = async () => {
- if (currentStep + 1 === TOTAL_STEPS) {
- await registrationMutation.mutateAsync(data);
- return;
- }
- await router.push({
- pathname: router.pathname,
- query: {
- step: getMaxStep(currentStep + 1),
- },
- });
- };
- void routePushOrSubmit();
- }, [data]);
- const CurrentStepComponent = React.useMemo(() => {
- if (currentStep === 0) {
- return RegisterFormStepOne;
- }
- return RegisterFormStepTwo;
- }, [currentStep]);
- return (
- <>
- {registrationMutation.error?.message &&
- <Alert variant="destructive">
- <AlertTitle>
- Er is iets misgegaan
- </AlertTitle>
- <AlertDescription>
- {registrationMutation.error?.message}
- </AlertDescription>
- </Alert>
- }
- <div className="text-center">
- <p className="font-medium">
- Stap {currentStep + 1} van {TOTAL_STEPS}
- </p>
- <p className="text-sm">
- {currentStep === 0 ? 'Persoonsgegevens' : 'Instelling'}
- </p>
- </div>
- <CurrentStepComponent
- onGoToNextStep={onGoToNextStep}
- onGoToPreviousStep={onGoToPreviousStep}
- isLoading={registrationMutation.isLoading}
- data={data}
- />
- </>
- );
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement