Connected signing up and signing in to back

This commit is contained in:
2023-07-29 10:41:54 +03:00
parent 0e5aeae491
commit 85472233a3
14 changed files with 228 additions and 168 deletions

View File

@ -1,50 +1,40 @@
import { FormEventHandler } from 'react'
import { useCallback, useState } from 'react'
import { Card, Tabs, Tab } from 'react-bootstrap'
import { useNavigate } from 'react-router-dom';
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../hooks/api';
import { setToken } from '../utils/auth';
import { AuthForm } from '../components';
import { AuthForm } from '../components'
import { isLiteralUnion } from '../utils/types'
const tabKeys = ['register', 'login'] as const
type TabKeys = typeof tabKeys[number]
const isTabKeys = (s: string | null): s is TabKeys => (
isLiteralUnion(s, tabKeys)
)
function LoginPage() {
const navigate = useNavigate()
const { doAuth, loading, error } = useAuth()
const [tab, setTab] = useState<TabKeys>('register')
const handleAuth = (newAccount: boolean): FormEventHandler<HTMLFormElement> => async (event) => {
event.preventDefault();
event.stopPropagation();
const formData = new FormData(event.currentTarget)
const data = {
email: formData.get('email') as string,
name: newAccount ? formData.get('name') as string : undefined,
surname: newAccount ? formData.get('surname') as string : undefined,
password: formData.get('password') as string
}
const token = import.meta.env.PROD ? (
await doAuth(data, newAccount)
) : (
'eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjUifQ.1S46AuB9E4JN9yLkqs30yl3sLlGLbgbrOCNKXiNK8IM'
)
if (token) {
setToken(token)
navigate(-1 - Number(import.meta.env.DEV))
}
}
const goBack = useCallback(() => (
navigate(-1 - Number(import.meta.env.DEV))
), [navigate])
return (
<Card className='m-4'>
<Card.Body>
<Tabs defaultActiveKey='register' fill justify className='mb-3'>
<Tabs
activeKey={tab}
onSelect={(k) => isTabKeys(k) && setTab(k)}
fill justify
className='mb-3'
>
<Tab eventKey='register' title='Регистрация'>
<AuthForm handleAuth={handleAuth(true)} register={true} loading={loading} error={error} />
<AuthForm goBack={goBack} register={true} />
</Tab>
<Tab eventKey='login' title='Вход'>
<AuthForm handleAuth={handleAuth(false)} register={false} loading={loading} error={error} />
<AuthForm goBack={goBack} register={false} />
</Tab>
</Tabs>
</Card.Body>