Skip to content

Instantly share code, notes, and snippets.

@JaiParakh
Last active December 21, 2020 08:35
Show Gist options
  • Save JaiParakh/a727a2980bd8d60b0edde39368696259 to your computer and use it in GitHub Desktop.
Save JaiParakh/a727a2980bd8d60b0edde39368696259 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StatusBar } from 'react-native';
import auth from '@react-native-firebase/auth';
import { GoogleSignin } from '@react-native-community/google-signin';
GoogleSignin.configure({
webClientId: '',
});
async function onGoogleButtonPress() {
// Get the users ID token
const { idToken } = await GoogleSignin.signIn();
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}
// Sign In Button
function GoogleSignIn() {
return (
<Button
title="Google Sign-In"
onPress={() => onGoogleButtonPress().then(() => console.log('Signed in with Google!')).catch(err => console.log(err))}
/>
);
}
// Sign Out Button
function GoogleSignOut() {
return (
<Button
title="Google Sign-Out"
onPress={() => auth().signOut().then(() => console.log('Signed Out From Google!')).catch(err => console.log(err))}
/>
);
}
function LoginApp() {
// Set an initializing state whilst Firebase connects
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
// Handle user state changes
function onAuthStateChanged(user) {
console.log(user)
setUser(user);
if (initializing){
setInitializing(false);
}
}
// useEffect is a react Hook.
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
if (initializing) return null;
if (!user) {
return (
<View>
<Text>Login</Text>
</View>
);
}
// If login is successfull we will display the user email
return (
<View>
<Text>Welcome {user.email}</Text>
<GoogleSignOut />
</View>
);
}
function App(){
return (
<>
<StatusBar barStyle="dark-content" />
<View style={{paddingTop: 60, paddingLeft: 15}}>
<GoogleSignIn />
<LoginApp />
</View>
</>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment