forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SigninBox.js
75 lines (65 loc) · 1.68 KB
/
SigninBox.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
import { useRef } from 'react'
import { useMutation, useApolloClient } from '@apollo/react-hooks'
import gql from 'graphql-tag'
import cookie from 'cookie'
import redirect from '../lib/redirect'
const SIGN_IN = gql`
mutation login($email: String, $password: String) {
login(email: $email, password: $password) {
token
}
}
`
// TODO: Find a better name for component.
const SigninBox = () => {
const client = useApolloClient()
const onCompleted = data => {
// Store the token in cookie
document.cookie = cookie.serialize('token', data.login.token, {
path: '/',
maxAge: 30 * 24 * 60 * 60 // 30 days
})
// Force a reload of all the current queries now that the user is
// logged in
client.cache.reset().then(() => {
redirect({}, '/')
})
}
const onError = error => {
// If you want to send error to external service?
console.error(error)
}
const [signinUser, { error }] = useMutation(SIGN_IN, {
onCompleted,
onError
})
const email = useRef(null)
const password = useRef(null)
return (
<form
onSubmit={e => {
e.preventDefault()
signinUser({
variables: {
email: email.current.value,
password: password.current.value
}
})
email.current.value = password.current.value = ''
}}
>
{error && <p>No user found with that information.</p>}
<input name='email' placeholder='Email' ref={email} />
<br />
<input
name='password'
placeholder='Password'
ref={password}
type='password'
/>
<br />
<button>Sign in</button>
</form>
)
}
export default SigninBox