Skip to content

Instantly share code, notes, and snippets.

@emil-alexandrescu
Created March 19, 2019 20:51
Show Gist options
  • Save emil-alexandrescu/fda821360b1966d738d830ccffb29e88 to your computer and use it in GitHub Desktop.
Save emil-alexandrescu/fda821360b1966d738d830ccffb29e88 to your computer and use it in GitHub Desktop.
import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';
import { GET_CURRENT_USER } from './withUser';
import { localStorage } from '@common/lib';
import gql from 'graphql-tag';
export const LOGIN_MUTATION = gql`
mutation loginMutation($usernameOrEmail: String!, $password: String!) {
loginUser(usernameOrEmail: $usernameOrEmail, password: $password) {
token
user {
id
firstName
lastName
username
email
role
}
}
}
`;
const withLogin = function(ComposedComponent) {
const LoginMutation = function(props) {
const { mutate } = props;
const executeLogin = async values => {
const response = await mutate({
variables: values,
update: (cache, { data }) => {
const {
loginUser: { user }
} = data;
cache.writeQuery({
query: GET_CURRENT_USER,
data: { currentUser: user }
});
}
});
localStorage.set('token', response.data.loginUser.token);
};
return <ComposedComponent {...props} login={executeLogin} />;
};
LoginMutation.propTypes = {
mutate: PropTypes.func.isRequired
};
return graphql(LOGIN_MUTATION)(LoginMutation);
};
export default withLogin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment