Skip to content

Commit

Permalink
refactor: move choose isMentor on last step
Browse files Browse the repository at this point in the history
  • Loading branch information
vitormarkis committed Jul 14, 2023
1 parent fc03afe commit eb0a2a6
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 84 deletions.
14 changes: 7 additions & 7 deletions src/components/_Layout/PlanPage.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import Button from "@components/Button";
import { CenteredContainer } from "@components/CenteredContainer";
import ProfileCardToggle from "@components/ProfileCardToggle";
import { Form } from "SIGNUP_SRC/components/Form";
import { Sign } from "SIGNUP_SRC/components/sign";
import { useMultistepForm } from "SIGNUP_SRC/hooks/useMultistepForm";
import Link from "next/link";
import React from "react";
import { useFormContext } from "react-hook-form";

export const PlanPage = () => {
const {
formState: { isSubmitting },
} = useFormContext();
const { setIsChoosingPlan } = useMultistepForm();

const handleNext = () => {
const handleGoBack = () => {
setIsChoosingPlan(false);
};

Expand All @@ -29,10 +31,8 @@ export const PlanPage = () => {
<ProfileCardToggle />
</div>
<Form.MultipleInRow className="mb-32">
<Sign.ButtonSecondary asChild>
<Link href="/signin">Voltar</Link>
</Sign.ButtonSecondary>
<Sign.ButtonPrimary onClick={handleNext} text="Próximo" />
<Sign.ButtonSecondary onClick={handleGoBack}>Voltar</Sign.ButtonSecondary>
<Sign.ButtonPrimary type="submit" disabled={isSubmitting} text="Enviar" />
</Form.MultipleInRow>
</section>
</CenteredContainer>
Expand Down
88 changes: 14 additions & 74 deletions src/components/_Layout/RegisterPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import StepperVertical from "@components/StepperVertical";
import { useMultistepForm } from "SIGNUP_SRC/hooks/useMultistepForm";
import { Personal } from "SIGNUP_SRC/steps/Personal";
import { IFormValues } from "SIGNUP_SRC/types";
import { PathValue, SubmitHandler, useFormContext } from "react-hook-form";
import { useFormContext } from "react-hook-form";
import { Location } from "SIGNUP_SRC/steps/Location";
import { Professional } from "SIGNUP_SRC/steps/Professional";
import { useCountriesFactory } from "SIGNUP_SRC/steps/factories/useCountriesFactory";
Expand All @@ -16,9 +16,6 @@ import { IUseGeoStates } from "SIGNUP_SRC/hooks/useGeoStates/types";
import { IUseGeoCities } from "SIGNUP_SRC/hooks/useGeoCities/types";
import { Form } from "SIGNUP_SRC/components/Form";
import { Sign } from "SIGNUP_SRC/components/sign";
import { toast } from "react-toastify";
import { useMutation } from "@apollo/client";
import { CREATE_USER } from "services/apollo/mutations";
import { useRouter } from "next/router";

export const validationPerStep: Record<number, (keyof IFormValues)[]> = {
Expand All @@ -37,18 +34,13 @@ const geoCitiesOptions: IUseGeoCities = {
export const RegisterPage = () => {
const { formCurrentStep, setFormCurrentStep, setIsChoosingPlan } = useMultistepForm();
const methods = useFormContext<IFormValues>();
const [createUser] = useMutation(CREATE_USER);
const router = useRouter();

const {
handleSubmit,
trigger,
formState: { errors, isSubmitting },
watch,
formState: { errors },
} = methods;

const isMentor = watch("isMentor");

const isInFirstStep = formCurrentStep === 0;
const isInLastStep = formCurrentStep === 2;

Expand All @@ -72,59 +64,19 @@ export const RegisterPage = () => {
);
const allStepValidationsResult = await Promise.all(allStepValidations);
const allValidationsPassed = allStepValidationsResult.every(Boolean);
if (allValidationsPassed) return setFormCurrentStep((currentStep) => currentStep + 1);
if (allValidationsPassed) {
if (isInLastStep) return setIsChoosingPlan(true);
return setFormCurrentStep((currentStep) => currentStep + 1);
}
};

const handleGoBackButton = () => {
if (isInFirstStep) {
return setIsChoosingPlan(true);
return router.push("/signin");
}
setFormCurrentStep((currentStep) => currentStep - 1);
};

const submitHandler: SubmitHandler<IFormValues> = async (formData) => {
const { repeatPassword, isTermsAccepted, ...createUserPayload } = formData;

try {
const response = await toast.promise(
createUser({
variables: {
input: createUserPayload,
},
}),
{
pending: "Aguarde um momento...",
success: `Usuário ${
formData.firstName ? formData.firstName : "MentorCycle"
} cadastrado com sucesso!`,
}
);
if (response.data.signUpUser) {
localStorage.removeItem("form-data");
router.push("/dashboard");
}
} catch (error) {
toast.error(getErrorMessage(error));
}
};

const getErrorMessage = (error: any) => {
const errorMessages: Record<string, string> = {
description: "A descrição precisa ter no mínimo 2 caracteres",
email: "Este email já possui cadastro",
};

for (const key in errorMessages) {
if (error.message.includes(key)) {
return errorMessages[key];
}
}

return error instanceof Error
? error.message
: "Não foi possivel concluir o cadastro, tente novamente mais tarde";
};

return (
<main className="flex flex-col">
<section className="h-28 border-b border-gray-03 hidden sm:flex">
Expand Down Expand Up @@ -157,10 +109,7 @@ export const RegisterPage = () => {
className="hidden lg:block"
/>
</aside>
<form
onSubmit={handleSubmit(submitHandler)}
className="relative form w-full mx-auto pt-12 lg:mx-0 mb-24 max-w-[43rem]"
>
<div className="relative w-full mx-auto pt-12 lg:mx-0 mb-24 max-w-[43rem]">
<div className="mb-3">
{formCurrentStep === 0 && <Personal />}
{formCurrentStep === 1 && (
Expand All @@ -175,22 +124,13 @@ export const RegisterPage = () => {
</div>
<Form.MultipleInRow>
<Sign.ButtonSecondary onClick={handleGoBackButton} text="Voltar" />
{isInLastStep && (
<Sign.ButtonPrimary
type="submit"
disabled={!shouldGoForward || isSubmitting}
text="Enviar"
/>
)}
{!isInLastStep && (
<Sign.ButtonPrimary
onClick={() => !isInLastStep && handleActionButton()}
disabled={!shouldGoForward}
text="Próximo"
/>
)}
<Sign.ButtonPrimary
onClick={handleActionButton}
disabled={!shouldGoForward}
text="Próximo"
/>
</Form.MultipleInRow>
</form>
</div>
</CenteredContainer>
</section>
</main>
Expand Down
57 changes: 54 additions & 3 deletions src/providers/signup/register/index.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import { FormProvider, useForm } from "react-hook-form";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { IFormValues } from "SIGNUP_SRC/types";
import { defaultValues } from "SIGNUP_SRC/constants";
import { signupFormSchema } from "SIGNUP_SRC/forms/signup";
import { MultistepFormContext } from "SIGNUP_SRC/hooks/useMultistepForm";
import { SetStateAction, useCallback, useMemo, useState } from "react";
import { toast } from "react-toastify";
import { useMutation } from "@apollo/client";
import { CREATE_USER } from "services/apollo/mutations";
import { useRouter } from "next/router";

interface Props {
children: JSX.Element;
}

const Providers = ({ children }: Props) => {
const [formCurrentStep, setFormCurrentStep] = useState(0);
const [isChoosingPlan, setIsChoosingPlan] = useState(true);
const [isChoosingPlan, setIsChoosingPlan] = useState(false);
const router = useRouter();
const [createUser] = useMutation(CREATE_USER);

const values = useMemo(
() => ({ formCurrentStep, isChoosingPlan }),
Expand All @@ -35,6 +41,49 @@ const Providers = ({ children }: Props) => {
resolver: zodResolver(signupFormSchema),
});

const submitHandler: SubmitHandler<IFormValues> = async (formData) => {
const { repeatPassword, isTermsAccepted, ...createUserPayload } = formData;

try {
const response = await toast.promise(
createUser({
variables: {
input: createUserPayload,
},
}),
{
pending: "Aguarde um momento...",
success: `Usuário ${
formData.firstName ? formData.firstName : "MentorCycle"
} cadastrado com sucesso!`,
}
);
if (response.data.signUpUser) {
localStorage.removeItem("form-data");
router.push("/dashboard");
}
} catch (error) {
toast.error(getErrorMessage(error));
}
};

const getErrorMessage = (error: any) => {
const errorMessages: Record<string, string> = {
description: "A descrição precisa ter no mínimo 2 caracteres",
email: "Este email já possui cadastro",
};

for (const key in errorMessages) {
if (error.message.includes(key)) {
return errorMessages[key];
}
}

return error instanceof Error
? error.message
: "Não foi possivel concluir o cadastro, tente novamente mais tarde";
};

return (
<MultistepFormContext.Provider
value={{
Expand All @@ -43,7 +92,9 @@ const Providers = ({ children }: Props) => {
setIsChoosingPlan: setIsChoosingPlanStepMemo,
}}
>
<FormProvider {...methods}>{children}</FormProvider>
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(submitHandler)}>{children}</form>
</FormProvider>
</MultistepFormContext.Provider>
);
};
Expand Down

0 comments on commit eb0a2a6

Please sign in to comment.