How to detect the login user is an existing user or a new user using firebase in react native. I have used Google auth to create the authentication but unfortunately I am not getting any field called isNewUser in return promise.
below is my code...
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);
}
function onAuthStateChanged(user) {
if (user) {
firestore()
.collection('Users')
.doc(user.uid)
.set({
user: user.displayName,
email: user.email,
photo: user.photoURL,
})
.then(() => {
console.log('User added!');
});
}
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
});
This is the return response I am getting.
{"displayName": "***", "email": "**@gmail.com", "emailVerified": true, "isAnonymous": false, "metadata": {"creationTime": 15960**412290, "lastSignInTime": 15960**65185}, "phoneNumber": null, "photoURL": "**", "providerData": [[Object]], "providerId": "firebase", "uid": "*******"}
My problem now is everytime once user successfully authenticate google signin method its adding data's to the firebase data base. Does there any way that I can detect the user is a new user or a existing user??
A help will be great and appreciable :)
The isNewUser
property is in the UserCredential
object, which is only available right after the call to signInWithCredential
.
const credentialPromise = auth().signInWithCredential(googleCredential);
credentialPromise.then((credential) => {
console.log(credential.additionalUserInfo.isNewUser);
})
You can determine whether the user is new from the auth state listener, by comparing the user's creation timestamp to their last sign in:
function onAuthStateChanged(user) {
if (user) {
if (user.metadata.creationTime <> user.metadata.lastSignInTime) {
...
}
}
}
Also see: