forked from vercel/next.js
/
signin.js
77 lines (70 loc) · 1.83 KB
/
signin.js
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
import React from 'react'
import Link from 'next/link'
import { withApollo } from '../apollo/client'
import gql from 'graphql-tag'
import { useMutation, useApolloClient } from '@apollo/react-hooks'
import Field from '../components/field'
import { getErrorMessage } from '../lib/form'
import { useRouter } from 'next/router'
const SignInMutation = gql`
mutation SignInMutation($email: String!, $password: String!) {
signIn(input: { email: $email, password: $password }) {
user {
id
email
}
}
}
`
function SignIn() {
const client = useApolloClient()
const [signIn] = useMutation(SignInMutation)
const [errorMsg, setErrorMsg] = React.useState()
const router = useRouter()
async function handleSubmit(event) {
event.preventDefault()
const emailElement = event.currentTarget.elements.email
const passwordElement = event.currentTarget.elements.password
try {
await client.resetStore()
const { data } = await signIn({
variables: {
email: emailElement.value,
password: passwordElement.value,
},
})
if (data.signIn.user) {
await router.push('/')
}
} catch (error) {
setErrorMsg(getErrorMessage(error))
}
}
return (
<>
<h1>Sign In</h1>
<form onSubmit={handleSubmit}>
{errorMsg && <p>{errorMsg}</p>}
<Field
name="email"
type="email"
autoComplete="email"
required
label="Email"
/>
<Field
name="password"
type="password"
autoComplete="password"
required
label="Password"
/>
<button type="submit">Sign in</button> or{' '}
<Link href="signup">
<a>Sign up</a>
</Link>
</form>
</>
)
}
export default withApollo(SignIn)