-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathLoginUser.js
More file actions
executable file
·84 lines (73 loc) · 2.2 KB
/
LoginUser.js
File metadata and controls
executable file
·84 lines (73 loc) · 2.2 KB
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
import React from 'react'
import { withRouter } from 'react-router-dom'
import { graphql, compose } from 'react-apollo'
import gql from 'graphql-tag'
class CreateLogin extends React.Component {
state = {
email: '',
password: '',
}
render () {
if (this.props.loggedInUserQuery.loading) {
return (
<div className='w-100 pa4 flex justify-center'>
<div>Loading</div>
</div>
)
}
// redirect if user is logged in
if (this.props.loggedInUserQuery.loggedInUser.id) {
console.warn('already logged in')
this.props.history.replace('/')
}
return (
<div className='w-100 pa4 flex justify-center'>
<div style={{ maxWidth: 400 }} className=''>
<input
className='w-100 pa3 mv2'
value={this.state.email}
placeholder='Email'
onChange={(e) => this.setState({email: e.target.value})}
/>
<input
className='w-100 pa3 mv2'
type='password'
value={this.state.password}
placeholder='Password'
onChange={(e) => this.setState({password: e.target.value})}
/>
{this.state.email && this.state.password &&
<button className='pa3 bg-black-10 bn dim ttu pointer' onClick={this.authenticateUser}>Log in</button>
}
</div>
</div>
)
}
authenticateUser = async () => {
const {email, password} = this.state
const response = await this.props.authenticateUserMutation({variables: {email, password}})
localStorage.setItem('graphcoolToken', response.data.authenticateUser.token)
this.props.history.replace('/')
}
}
const AUTHENTICATE_USER_MUTATION = gql`
mutation AuthenticateUserMutation ($email: String!, $password: String!) {
authenticateUser(email: $email, password: $password) {
token
}
}
`
const LOGGED_IN_USER_QUERY = gql`
query LoggedInUserQuery {
loggedInUser {
id
}
}
`
export default compose(
graphql(AUTHENTICATE_USER_MUTATION, {name: 'authenticateUserMutation'}),
graphql(LOGGED_IN_USER_QUERY, {
name: 'loggedInUserQuery',
options: { fetchPolicy: 'network-only' }
})
)(withRouter(CreateLogin))