Skip to content

Instantly share code, notes, and snippets.

@jayliew

jayliew/.js Secret

Last active July 18, 2019 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayliew/3b7cff4b6f52a58d6034f05a8ae6794a to your computer and use it in GitHub Desktop.
Save jayliew/3b7cff4b6f52a58d6034f05a8ae6794a to your computer and use it in GitHub Desktop.
React GraphQL mutation using Ant Design that triggers onSubmit handler
import React from 'react'
//import './App.css'
import gql from 'graphql-tag'
import { Mutation } from 'react-apollo'
import { Input, Button, Form, Icon } from 'antd'
import { Alert, Spin } from 'antd'
//import 'antd/dist/antd.css'
import { __log } from '../utils/log.js'
////////////////////////////////////////////////////
//
// NOTE: The default export is wrapped in a HOC
//
////////////////////////////////////////////////////
const LOGIN_MUTATION = gql`
mutation LoginMutation($email: String!, $password: String!) {
login(email: $email, password: $password)
}
`
class HorizontalLoginForm extends React.Component {
constructor (props) {
super(props)
this.state = {
authenticationAttempts: 0,
authenticated: false,
expectingResponse: false
}
}
componentDidMount() {
// To disabled submit button at the beginning.
__log(`child componentDidMount()`)
this.props.form.validateFields()
}
componentWillUnmount(){
__log(`child will unmount`)
}
handleOnSubmit = e => {
e.preventDefault()
debugger
__log(`onSubmit: authenticationAttempts: ${this.state.authenticationAttempts}, authenticated: ${this.state.authenticated}`)
this.props.form.validateFields((err, values) => {
if (!err) {
this.setState({expectingResponse: true})
// anything else needed to be done before firing GraphQL query
}
})
} // handleOnSubmit
_hasErrors = (fieldsError) => {
return Object.keys(fieldsError).some(field => fieldsError[field])
}
_postLoginSubmit = async (data) => { // handle response from GraphQL query
__log(`_postLoginSubmit() data.login: `, data.login)
this.setState( (prevState, props) => ({
expectingResponse: false,
authenticationAttempts: prevState.authenticationAttempts + 1
}))
if(data && data.login != null){ // if authenticated
this.setState({ authenticated: true },
() => {
localStorage.setItem('LocalStorageAuthTokenKeyName', data.login)
__log(`_postLoginSubmit() have set authenticated to true`)
this.props.isLoggedInCheck()
})
}else{ // if auth fails
this.setState({ authenticated: false },
() => {
localStorage.removeItem('LocalStorageAuthTokenKeyName')
__log(`_postLoginSubmit() have set authenticated to false`)
this.props.isLoggedInCheck()
})
}
} // _postLoginSubmit
render() {
const { getFieldValue, getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form
// Only show error after a field is touched
const usernameError = isFieldTouched('username') && getFieldError('username')
const passwordError = isFieldTouched('password') && getFieldError('password')
__log(`child render() authenticationAttempts ${this.state.authenticationAttempts}`)
__log(`child render() authenticated ${this.state.authenticated}`)
return (
<Form layout="inline" onSubmit={this.handleOnSubmit}>
<Form.Item validateStatus={usernameError ? 'error' : ''} help={usernameError || ''}>
{
getFieldDecorator(
'username',
{
rules: [{ required: true, min: 1, max: 255, whitespace: true, message: 'Missing username' }],
}
)(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Username"
/>,
)
}
</Form.Item>
<Form.Item validateStatus={passwordError ? 'error' : ''} help={passwordError || ''}>
{getFieldDecorator('password', {
rules: [{ required: true, min: 1, max: 255, whitespace: true, message: 'Missing password' }],
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
/>,
)}
</Form.Item>
<Form.Item>
<Mutation
mutation={LOGIN_MUTATION}
variables={{ email: getFieldValue('username'), password: getFieldValue('password') }}
onCompleted={data => this._postLoginSubmit(data)}
>
{
(mutation) => {
return (
<Button
type='primary'
htmlType='submit'
className="pointer mr2 button"
onClick={mutation} disabled={this._hasErrors(getFieldsError())}
>
Login
</Button>
)
}
}
</Mutation>
&nbsp; &nbsp;
{ this.state.expectingResponse ? <Spin /> : null}
{ this.state.authenticationAttempts > 0 && this.state.authenticated === false ? <Alert message="Email or password incorrect. Try again?" type="error" /> : null}
</Form.Item>
</Form>
)
}
}
export default Form.create({name: 'horizontal_login'})(HorizontalLoginForm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment