Home > OS >  implementing custom logic for phoneauth signup in my react-native firebase project
implementing custom logic for phoneauth signup in my react-native firebase project

Time:06-10

I was trying to make a custom logic for signup phoneauth with Firebase that reads phone number from Firestore. If already present it shows "Already exist else register a new account". But while implementing I am getting errors like if and else both are executed or multiple documents are created while registering. Help me with it or refer to any other article will be a great help.

const onRegisterPress = () => {
     firestore().collection('InternData').get().then((querySnapshot) => {
       querySnapshot.forEach((doc) => {
           if(`${doc.data().phoneNumber}` == phoneNumber)
            return alert('Already registered. Try to login first')
         else{
           firestore()
           .collection('InternData')
           .add({
             phoneNumber: phoneNumber,
             fullName: fullName,
             date: date,
             expertiseIn: expertiseIn
           }).then(() => {
             // navigation.navigate('InternInfo')
             console.log('otp screen')
             onSubmit(phoneNumber)
           })
         }
       })
     })

CodePudding user response:

This query firestore().collection('InternData').get() would fetch all the documents and check each document if the phoneNumber exists on it causing you to execute your conditions multiple times to each documents found on the InternData collection.

For your use-case, I would suggest using the where() method instead. The query should be like this:

firestore()
.collection('InternData')
.where('phoneNumber', '==', phoneNumber)
.get()

The query above will fetch all the documents that match the value of the fieldname: "phoneNumber" with the value of the variable phoneNumber.

For reference, here's a full sample code:

firestore()
.collection('InternData')
.where('phoneNumber', '==', phoneNumber)
.get()
.then((querySnapshot) => {
    // If no match is found, create a new document to the collection.
    if (querySnapshot.empty) {        
        firestore()
        .collection('InternData')
        .add({
            phoneNumber: phoneNumber,
            fullName: fullName,
            date: date,
            expertiseIn: expertiseIn
        }).then(() => {
            // navigation.navigate('InternInfo')
            console.log('otp screen')
            onSubmit(phoneNumber)
        })
    } else {
        // This will trigger if there's a result for your query.
        return alert('Already registered. Try to login first')
    }
})
.catch((error) => {
    console.log("Error getting documents: ", error);
});

For more information, you may check out this documentations:

  • Related