I have implemented Apple Sign In to my React Native App using Firebase and the Sign In process is working fine.
I am adding the User details to a Database Collection named 'users' in Firestore.
When the user re-signs in the data which is added to the collection from their Profile gets overwritten.
How can I check if user exists so the collection document is only created once?
My code is as follows
appleSignIn: async () => {
try {
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
});
if(!appleAuthRequestResponse.identityToken) {
throw 'Apple Sign-In failed - no identify token returned';
}
const { identityToken, nonce } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
await auth().signInWithCredential(appleCredential);
firestore().collection('users').doc(auth().currentUser.uid)
.set({
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
})
} catch (e) {
console.log(e);
}
},
CodePudding user response:
You can check if is user exist in users
collection.
...
await auth().signInWithCredential(appleCredential);
const existingUserDoc = await firestore().collection('users').doc(auth().currentUser.uid).get();
if (existingUserDoc && existingUserDoc.exists) {
// you can do something here. user details already created.
} else {
firestore().collection('users').doc(auth().currentUser.uid)
.set({
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
});
}
...
Or more simply way if user document exists you can pass firestore().collection('users').doc('uid').set({...})
execution.
...
await auth().signInWithCredential(appleCredential);
const existingUserDoc = await firestore().collection('users').doc(auth().currentUser.uid).get();
// ignore execution of setting user deatils.
if (!existingUserDoc && !existingUserDoc.exists) {
firestore().collection('users').doc(auth().currentUser.uid)
.set({
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
});
}
...