Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React-hook-form implementiert #4

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@fontsource/roboto": "5.0.2",
"@hookform/resolvers": "^3.9.1",
"@mui/icons-material": "^6.2.1",
"@mui/material": "^6.2.1",
"@mui/x-date-pickers": "^7.23.3",
Expand All @@ -28,6 +29,7 @@
"next": "15.1.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-hook-form": "^7.54.2",
"sonner": "0.3.5",
"yup": "1.2.0",
"zod": "^3.24.1"
Expand Down
12 changes: 6 additions & 6 deletions src/app/(project)/(auth)/login/page.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
"use client"

import { Container } from "@mui/material";
import { Box } from "@mui/system";
import {Container} from "@mui/material";
import {Box} from "@mui/system";
import Link from "next/link";
import { useEffect } from "react";
import {useEffect} from "react";
import {useAuth} from "@/context/AuthContext";
import {LoginForm, LoginFormData} from "@/components/auth/LoginForm";
import {AuthPaper} from "@/components/auth/AuthPaper";
import {useRouter} from "next/navigation";

export default function LoginPage() {
const { user, login } = useAuth();
const {user, login} = useAuth();
const router = useRouter();

useEffect(() => {
if (user) {
router.push("/");
}
}, [user]);
}, [user, router]);

const onLogin = async (data: LoginFormData, callback: () => void) => {
login(data.email, data.password);
Expand All @@ -38,7 +38,7 @@ export default function LoginPage() {
title="Welcome to the Chuck Norris Challenge!"
subtitle="Login"
>
<LoginForm onSubmit={onLogin} />
<LoginForm onSubmit={onLogin}/>
</AuthPaper>
<Box
sx={{
Expand Down
2 changes: 1 addition & 1 deletion src/app/(project)/(auth)/password-reset/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoginPage() {
if (user) {
router.push("/");
}
}, [user]);
}, [user, router]);

const onPasswordReset = async (
data: PasswordResetFormData,
Expand Down
2 changes: 1 addition & 1 deletion src/app/(project)/(auth)/signup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function LoginPage() {
if (user) {
router.push("/");
}
}, [user]);
}, [user, router]);

const onSignup = async (data: SignupFormData, callback: () => void) => {
await signup(data.email, data.password);
Expand Down
2 changes: 1 addition & 1 deletion src/app/(project)/home/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function Page() {
if (!user) {
router.push("/login");
}
}, [user]);
}, [user, router]);


return (
Expand Down
191 changes: 91 additions & 100 deletions src/components/auth/LoginForm.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"use client";

import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
import {Box} from "@mui/material";
import {Form, Formik} from "formik";
import {Box, Button, TextField} from "@mui/material";
import Link from "next/link";
import {useState} from "react";
import {Controller, useForm} from "react-hook-form";
import {z} from "zod";
import {FormikTextField} from "@/components/formikInputs/FormikTextField";
import {LoadingButton} from "@/components/default/LoadingButton";
import {zodResolver} from "@hookform/resolvers/zod";

interface LoginFormProps {
onSubmit: (data: LoginFormData, callback: () => void) => void;
Expand All @@ -19,118 +18,110 @@ export interface LoginFormData {
}

const loginSchema = z.object({
email: z.string()
email: z
.string()
.nonempty("This field is required")
.email("Invalid email address"),
password: z.string()
.nonempty("This field is required"),
password: z.string().nonempty("This field is required"),
});

export const LoginForm: React.FC<LoginFormProps> = (props) => {
export const LoginForm: React.FC<LoginFormProps> = ({onSubmit}) => {
const [loading, setLoading] = useState(false);
const [emailForReset, setEmailForReset] = useState("");

const initialValues: LoginFormData = {
email: "",
password: "",
};
const {
control,
handleSubmit,
formState: {errors},
watch,
} = useForm<LoginFormData>({
defaultValues: {
email: "",
password: "",
},
resolver: zodResolver(loginSchema),
});

const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setEmailForReset(value);
};
const emailValue = watch("email");

const onSubmit = (data: LoginFormData) => {
const onFormSubmit = (data: LoginFormData) => {
setLoading(true);

setEmailForReset(data.email);

props.onSubmit(data, () => {
onSubmit(data, () => {
setLoading(false);
});
};

const validate = (values: LoginFormData) => {
try {
loginSchema.parse(values);
return {};
} catch (err) {
const errors: Partial<LoginFormData> = {};
if (err instanceof z.ZodError) {
err.errors.forEach((error) => {
const field = error.path[0];
if (field && typeof field === "string") {
errors[field as keyof LoginFormData] = error.message;
}
});
}
return errors;
}
};

return (
<Formik<LoginFormData>
initialValues={initialValues}
validate={validate}
onSubmit={(values) => {
onSubmit(values);
<form
onSubmit={handleSubmit(onFormSubmit)}
style={{
display: "flex",
flexDirection: "column",
maxWidth: "400px",
}}
>
{({handleSubmit}) => (
<Form onSubmit={handleSubmit} placeholder={undefined} onPointerEnterCapture={undefined}
onPointerLeaveCapture={undefined}>
<Box
sx={{
display: "flex",
flexDirection: "column",
maxWidth: "400px",
}}
>
<FormikTextField
name="email"
type="email"
label="Enter your email"
onChange={handleEmailChange}
/>
<FormikTextField
name="password"
type="password"
label="Enter your password"
sx={{
marginTop: 2,
}}
/>
<Box
sx={{
display: "flex",
flexDirection: "row-reverse",
marginTop: 0.5,
}}
>
<Link
href={{
pathname: "/password-reset",
query: emailForReset ? {email: emailForReset} : {},
}}
>
{"Reset Password"}
</Link>
</Box>
<LoadingButton
variant="contained"
type="submit"
endIcon={<ArrowForwardIcon/>}
loading={loading}
sx={{
marginTop: 2,
marginBottom: 1,
}}
>
Login
</LoadingButton>
</Box>
</Form>
)}
</Formik>
<Controller
name="email"
control={control}
render={({field}) => (
<TextField
{...field}
label="Enter your email"
type="email"
fullWidth
error={!!errors.email}
helperText={errors.email?.message}
margin="normal"
/>
)}
/>

<Controller
name="password"
control={control}
render={({field}) => (
<TextField
{...field}
label="Enter your password"
type="password"
fullWidth
error={!!errors.password}
helperText={errors.password?.message}
margin="normal"
sx={{marginTop: 2}}
/>
)}
/>

<Box
sx={{
display: "flex",
flexDirection: "row-reverse",
marginTop: 0.5,
}}
>
<Link
href={{
pathname: "/password-reset",
query: emailValue ? {email: emailValue} : {},
}}
>
{"Reset Password"}
</Link>
</Box>

<Button
variant="contained"
type="submit"
endIcon={<ArrowForwardIcon/>}
disabled={loading}
sx={{
marginTop: 2,
marginBottom: 1,
}}
>
{loading ? "Loading..." : "Login"}
</Button>
</form>
);
};
Loading