forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegisterBox.js
73 lines (65 loc) · 1.88 KB
/
RegisterBox.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
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 CREATE_USER = gql`
mutation register($email: String, $name: String, $password: String) {
register(email: $email, name: $name, password: $password) {
token
}
}
`
const RegisterBox = () => {
const client = useApolloClient()
const onCompleted = data => {
// Store the token in cookie
document.cookie = cookie.serialize('token', data.register.token, {
maxAge: 30 * 24 * 60 * 60, // 30 days
path: '/' // make cookie available for all routes underneath "/"
})
// 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 [create, { error }] = useMutation(CREATE_USER, { onCompleted, onError })
const name = useRef(null)
const email = useRef(null)
const password = useRef(null)
return (
<form
onSubmit={e => {
e.preventDefault()
create({
variables: {
name: name.current.value,
email: email.current.value,
password: password.current.value
}
})
name.current.value = email.current.value = password.current.value = ''
}}
>
{error && <p>Issue occurred while registering :(</p>}
<input name='name' placeholder='Name' ref={name} />
<br />
<input name='email' placeholder='Email' ref={email} />
<br />
<input
name='password'
placeholder='Password'
ref={password}
type='password'
/>
<br />
<button>Register</button>
</form>
)
}
export default RegisterBox