Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created August 26, 2016 19:50
Show Gist options
  • Save AndrewIngram/0c68add1c458aaca86c4adefaaa16eca to your computer and use it in GitHub Desktop.
Save AndrewIngram/0c68add1c458aaca86c4adefaaa16eca to your computer and use it in GitHub Desktop.
Relay login
/* @flow */
import React from 'react';
import Relay from 'react-relay';
import cookies from 'browser-cookies';
import LoginForm from './LoginForm';
import LoginMutation from './mutations/LoginMutation';
class Login extends React.Component {
props: {
relay: Object,
viewer: Object,
};
state: {
isSubmitting: boolean,
errorMsg: ?string,
};
constructor(props) {
super(props);
this.state = {
isSubmitting: false,
errorMsg: null,
};
}
submit = (values) => {
const { relay, viewer } = this.props;
this.setState({isSubmitting: true});
relay.commitUpdate(
new LoginMutation({
values,
viewer,
}), {
onSuccess: ({ login }) => {
const { token } = login;
const { currentUser } = login.viewer;
if (token && currentUser) {
cookies.set('token', token);
/* do something else, like navigate, or close the form */
} else {
this.setState({errorMsg: 'BAD!', isSubmitting: false});
}
}
},
);
};
render() {
const { errorMsg, isSubmitting } = this.state;
return (
<div>
{errorMsg}
<LoginForm isSubmitting={isSubmitting} onSubmit={this.submit} initialModel={{
username: '',
password: '',
}} />
</div>
);
}
}
export default Relay.createContainer(Login, {
fragments: {
node: () => Relay.QL`
fragment on Viewer {
${LoginMutation.getFragment('viewer')}
}
`,
},
});
/* @flow */
import Relay from 'react-relay';
export default class LoginMutation extends Relay.Mutation {
static fragments = {
viewer: () => Relay.QL`
fragment on Viewer {
id
}
`,
};
getMutation() {
return Relay.QL`
mutation { login }
`;
}
getFatQuery() {
return Relay.QL`
fragment on LoginPayload @relay(pattern: true) {
viewer
token
}
`;
}
getConfigs() {
return [{
type: 'FIELDS_CHANGE',
fieldIDs: {
viewer: this.props.viewer.id,
},
}, {
type: 'REQUIRED_CHILDREN',
children: [Relay.QL`
fragment on LoginPayload {
token
}
`],
}];
}
getVariables() {
return this.props.values;
}
}
/* @flow */
import cookies from 'browser-cookies';
import RelayDefaultNetworkLayer from 'react-relay/lib/RelayDefaultNetworkLayer';
export default class NetworkLayer extends RelayDefaultNetworkLayer {
constructor(uri, init) {
super(uri, init);
}
set _init(init) {
this.__init = init;
}
get _init() {
const token = cookies.get('token');
if (!token) {
return this.__init;
}
const { headers, other } = this.__init;
return {
...other,
headers: {
Authorization: `Bearer ${token}`,
...headers,
},
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment