-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.component.tsx
73 lines (62 loc) · 2.05 KB
/
auth.component.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// inspired by https://mantine.dev/form/use-form/
import { isFormType } from "@features/auth/auth.types";
import { DEFAULT_FORM_TYPE } from "@features/auth/components/auth-form/auth-form.constants";
import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import type { FormType } from "@features/auth/auth.types";
import type { Dispatch, SetStateAction } from "react";
const AuthForm = dynamic(
() => import(`@features/auth/components/auth-form/auth.form`),
);
const AuthFormSkeleton = dynamic(
() =>
import(`@features/auth/components/auth-form/skeleton/auth-form.skeleton`),
);
export type AuthComponentProps = {
setTitle: Dispatch<SetStateAction<string>>;
};
const AuthComponent = ({ setTitle }: AuthComponentProps): JSX.Element => {
const router = useRouter();
const { form: formQuery } = router.query;
const [formType, setFormType] = useState<FormType>(DEFAULT_FORM_TYPE);
useEffect(() => {
setTitle(router.isReady ? formType : DEFAULT_FORM_TYPE);
}, [formType, router.isReady, setTitle]);
// once router is ready set `formType` if `formQuery` contains a valid value
useEffect(() => {
if (
router.isReady &&
typeof formQuery === `string` &&
isFormType(formQuery)
) {
setFormType(formQuery);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router.isReady]);
// whenever `formType` is changed update query params accordingly
useEffect(() => {
if (router.isReady) {
void router.push(
{
pathname: router.pathname,
query: { ...router.query, form: formType },
},
`${router.pathname}?form=${formType}`,
{ shallow: true },
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formType]);
return router.isReady ? (
<AuthForm
formType={formType}
toggleFormType={() =>
setFormType((previous) => (previous === `login` ? `register` : `login`))
}
/>
) : (
<AuthFormSkeleton />
);
};
export default AuthComponent;