Open History to see the last commit
1import { useRouter } from '@tanstack/react-router'
2import { useServerFn } from '@tanstack/react-start'
3import { useMutation } from '../hooks/useMutation'
4import { loginFn } from '../routes/_authed'
5import { signupFn } from '../routes/signup'
6import { Auth } from './Auth'
7β
8export function Login() {
9 const router = useRouter()
10β
11 const loginMutation = useMutation({
12 fn: loginFn,
13 onSuccess: async (ctx) => {
14 if (!ctx.data?.error) {
15 await router.invalidate()
16 router.navigate({ to: '/' })
17 return
18 }
19 },
20 })
21β
22 const signupMutation = useMutation({
23 fn: useServerFn(signupFn),
24 })
25β
26 return (
27 <Auth
28 actionText="Login"
29 status={loginMutation.status}
30 onSubmit={(e) => {
31 const formData = new FormData(e.target as HTMLFormElement)
32β
33 loginMutation.mutate({
34 data: {
35 email: formData.get('email') as string,
36 password: formData.get('password') as string,
37 },
38 })
39 }}
40 afterSubmit={
41 loginMutation.data ? (
42 <>
43 <div className="text-red-400">{loginMutation.data.message}</div>
44 {loginMutation.data.error &&
45 loginMutation.data.message === 'Invalid login credentials' ? (
46 <div>
47 <button
48 className="text-blue-500"
49 onClick={(e) => {
50 const formData = new FormData(
51 (e.target as HTMLButtonElement).form!,
52 )
53β
54 signupMutation.mutate({
55 data: {
56 email: formData.get('email') as string,
57 password: formData.get('password') as string,
58 },
59 })
60 }}
61 type="button"
62 >
63 Sign up instead?
64 </button>
65 </div>
66 ) : null}
67 </>
68 ) : null
69 }
70 />
71 )
72}