forked from reduxjs/redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLogin.tsx
111 lines (101 loc) · 2.74 KB
/
Login.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import * as React from 'react'
import {
Input,
InputGroup,
InputRightElement,
VStack,
Button,
Divider,
Center,
Box,
useToast,
} from '@chakra-ui/react'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { ProtectedComponent } from './ProtectedComponent'
import { useLoginMutation } from '../../app/services/auth'
import type { LoginRequest } from '../../app/services/auth'
function PasswordInput({
name,
onChange,
}: {
name: string
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void
}) {
const [show, setShow] = React.useState(false)
const handleClick = () => setShow(!show)
return (
<InputGroup size="md">
<Input
pr="4.5rem"
type={show ? 'text' : 'password'}
placeholder="Enter password"
name={name}
onChange={onChange}
/>
<InputRightElement width="4.5rem">
<Button h="1.75rem" size="sm" onClick={handleClick}>
{show ? 'Hide' : 'Show'}
</Button>
</InputRightElement>
</InputGroup>
)
}
export const Login = () => {
const dispatch = useDispatch()
const navigate = useNavigate()
const toast = useToast()
const [formState, setFormState] = React.useState<LoginRequest>({
username: '',
password: '',
})
const [login, { isLoading }] = useLoginMutation()
const handleChange = ({
target: { name, value },
}: React.ChangeEvent<HTMLInputElement>) =>
setFormState((prev) => ({ ...prev, [name]: value }))
return (
<Center h="500px">
<VStack spacing="4">
<Box>Hint: enter anything, or leave it blank and hit login</Box>
<InputGroup>
<Input
onChange={handleChange}
name="username"
type="text"
placeholder="Email"
/>
</InputGroup>
<InputGroup>
<PasswordInput onChange={handleChange} name="password" />
</InputGroup>
<Button
isFullWidth
onClick={async () => {
try {
await login(formState).unwrap()
// Being that the result is handled in extraReducers in authSlice,
// we know that we're authenticated after this, so the user
// and token will be present in the store
navigate('/')
} catch (err) {
toast({
status: 'error',
title: 'Error',
description: 'Oh no, there was an error!',
isClosable: true,
})
}
}}
colorScheme="green"
isLoading={isLoading}
>
Login
</Button>
<Divider />
<ProtectedComponent />
</VStack>
</Center>
)
}
export default Login