import React, { Component } from 'react'
import { Container, Header, Input, Button, Message } from 'semantic-ui-react'
import { gql, graphql } from 'react-apollo'
class Register extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
email: '',
password: '',
errors: {}
}
}
onChange = e =>
this.setState({
[e.target.name]: e.target.value
})
onSubmit = async () => {
const { errors: deleted, ...variables } = this.state
const response = await this.props.mutate({ variables })
const { ok, errors } = response.data.register
if (ok)
this.props.history.push('/')
else {
const errs = {}
errors.forEach(({ path, message }) => {
errs[path] = message
})
this.setState({ errors: errs })
}
console.log(response)
}
render() {
const { username, email, password, errors } = this.state
return (
<Container text>
<Header as="h2">Register</Header>
<Input
fluid
error={!!errors.username}
name="username"
value={username}
onChange={this.onChange}
placeholder="username"
/>
<Input
fluid
error={!!errors.email}
name="email"
value={email}
onChange={this.onChange}
type="email"
placeholder="email"
/>
<Input
fluid
error={!!errors.password}
name="password"
value={password}
onChange={this.onChange}
type="password"
placeholder="password"
/>
<Button onClick={this.onSubmit}>submit</Button>
{errors.username || errors.password || errors.email ? (
<Message error header="Error occured" list={Object.values(errors)} />
) : null}
</Container>
)
}
}
const registerMutation = gql`
mutation($username: String!, $email: String!, $password: String!) {
register(username: $username, email: $email, password: $password) {
ok
errors {
path
message
}
}
}
`
export default graphql(registerMutation)(Register)