Skip to content

Instantly share code, notes, and snippets.

@luandevpro luandevpro/Login.js
Last active Jun 29, 2019

Embed
What would you like to do?
import React, { useEffect } from 'react';
import gql from 'graphql-tag';
import { auth, googleAuthProvider, database } from '../lib/firebase';
import initialApollo from '../lib/initialApollo';
const getUser = gql`
query getUser($id: String!) {
user_by_pk(id: $id) {
id
email
photoURL
displayName
}
}
`;
const addUser = gql`
mutation insert_user($objects: [user_insert_input!]!) {
insert_user(
objects: $objects
on_conflict: { constraint: user_pkey, update_columns: [displayName, photoURL, email] }
) {
returning {
id
photoURL
}
}
}
`;
function Login() {
useEffect(
() =>
auth.onAuthStateChanged(async user => {
if (user) {
const metadataRef = await database.ref(`metadata/${user.uid}/refreshTime`);
const callback = async () => {
const token = await user.getIdToken();
const idTokenResult = await user.getIdTokenResult();
const hasuraClaim = await idTokenResult.claims['https://hasura.io/jwt/claims'];
if (hasuraClaim) {
const initialApolloGraph = initialApollo(token);
initialApolloGraph
.query({
query: getUser,
variables: {
id: user.uid,
},
})
.then(users => {
if (users.data.user_by_pk !== null) {
console.log(users);
} else {
initialApolloGraph
.mutate({
mutation: addUser,
variables: {
objects: [
{
id: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
},
],
},
context: {},
})
.then(() => console.log('success'))
.catch(result => console.log(result));
}
})
.catch(err => {
console.log(err);
});
}
};
metadataRef.on('value', callback);
}
}),
[]
);
const signinWithGoogle = async () => {
try {
await auth.signInWithPopup(googleAuthProvider);
} catch (error) {
console.log(error);
}
};
const signOut = async () => {
try {
await auth.signOut();
} catch (error) {
console.log(error);
}
};
return (
<div>
<button type="button" onClick={signinWithGoogle}>
Login
</button>
<button type="button" onClick={signOut}>
Sign out
</button>
</div>
);
}
export default Login;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.