Created
March 19, 2019 20:51
-
-
Save emil-alexandrescu/fda821360b1966d738d830ccffb29e88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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