How To Setup Firestore For App Database ?


How To Setup Firestore For App Database

Table Of Contents:

  1. Login To Your Google Firebase Console.

Step-1: Login To Your Google Firebase Console.

  1. Login To Your Google Firebase Console and clicks on the Create Database.

 (2) Choose The Location Of Your Server

 (3) Select production Mode

 (4) Ready To Go

Step-2: Create Collections For Firestore

Step-3: Accessing Your Firestore Database.

Install Required Libraries
# Install & setup the app module
npm install @react-native-firebase/app

# Install the firestore module
npm install @react-native-firebase/firestore
  • check for other two libraries, npm install @react-native-firebase/app and    npm install @react-native-firebase/auth all should be of same version.
  • If not install the latest version again, npm install @react-native-firebase/auth@latest
    "@react-native-firebase/app": "^21.10.0",
    "@react-native-firebase/auth": "^21.10.0",
    "@react-native-firebase/firestore": "^21.10.0",
Make Connection To Firestore Database
  • Follow this link to set up your FireStore Setup
https://www.praudyog.com/react-native-tutorials/how-to-setup-firebase-for-mobile-number-authentication/
Import The firestore Library
import firestore from '@react-native-firebase/firestore';
Create FirestoreServices.ts File Unser src/Services/FirestoreServices.ts Folder.
import firestore, { FirebaseFirestoreTypes } from '@react-native-firebase/firestore';

interface PersonalOrBusiness {
    userId: string;
    isPersonal: boolean;
    isBusiness: boolean;
}

interface SignUpDetails {
    userId: string;
    mobileNumber: string;
    signupDateTime: FirebaseFirestoreTypes.Timestamp;
}

interface PersonalDetails {
  userId: string;
  fullName: string;
  gender: string;
  primaryContact: number;
  emergencyContact: number;
  workingDays: string;
  bestTimeFrom: string;
  bestTimeTo: string;
  doNotDisturbFrom: string;
  doNotDisturbTo: string;
  languagePreferences: string;
}

interface BusinessDetails {
    userId: string;
    businessName: string;
    industry: string;
    website: string;
    contactEmail: string;
    primaryContact: number;
    businessAddress: string;
    operationalFrom: string;
    operationalTo: string;
    businessDescription: string;
  }

interface UserSettings {
  userId: string;
  autoCallAnswering: boolean;
  fraudCallIdentification: boolean;
  emergencyCallAlert: boolean;
  drivingMode: boolean;
  callRecording: boolean;
  callerLocationDisplay: boolean;
  callerNameAnnouncement: boolean;
  callerSentimentAnalysis: boolean;
}

export const storeBusinessOrPersonalUse = async (data: PersonalOrBusiness) => {
    try {
      await firestore().collection('ammyai_user_personal_business_use').doc(data.userId).set(data);
      console.log('Business Or Personal Use Added Successfully');
    } catch (error) {
      console.error('Error Adding SignUp Details: ', error);
    }
  };

export const storeSignUpDetails = async (data: SignUpDetails) => {
  try {
    await firestore().collection('ammyai_user_signup_details').doc(data.userId).set(data);
    console.log('SignUp Details Added Successfully');
  } catch (error) {
    console.error('Error Adding SignUp Details: ', error);
  }
};

export const storePersonalDetails = async (data: PersonalDetails) => {
  try {
    await firestore().collection('ammyai_user_personal_details').doc(data.userId).set(data);
    console.log('Personal Details Added Successfully');
  } catch (error) {
    console.error('Error Adding Personal Details: ', error);
  }
};

export const storeBusinessDetails = async (data: BusinessDetails) => {
  try {
    await firestore().collection('ammyai_user_business_details').doc(data.userId).set(data);
    console.log('Business Details Added Successfully');
  } catch (error) {
    console.error('Error Adding Business Details: ', error);
  }
};

export const storeUserSettings = async (data: UserSettings) => {
  try {
    await firestore().collection('ammyai_user_required_settings').doc(data.userId).set(data);
    console.log('User Settings Added Successfully');
  } catch (error) {
    console.error('Error Adding User Settings: ', error);
  }
};
Access The Firestore Database.
import firestore, { FirebaseFirestoreTypes } from '@react-native-firebase/firestore';
const userRef = firestore()
        .collection('ammyai_user_signup_details')
        .where('user_mobile_number', '==', phoneNumber);
const querySnapshot = await userRef.get();
if (!querySnapshot.empty) {
        // User already exists, fetch existing userId
        const existingUserData = querySnapshot.docs[0].data();
        const existingUserId = existingUserData.userId;
        console.log('User Already Exists With UserId:', existingUserId);
        setUserId(existingUserId); // Set context userId
        setIsNewUser(false)
      } else {
        // User does not exist, generate new userId
        const newUserId: string = await generateCustomUID();
        setUserId(newUserId);
        setIsNewUser(true)
        const userData = {
          userId: newUserId,
          user_mobile_number: phoneNumber,
          user_signup_date_time: firestore.FieldValue.serverTimestamp(),
        };
  
        await storeSignUpDetails(userData); // Store signup details in Firestore
        console.log('New User Created With UserId:', newUserId);
      }

Leave a Reply

Your email address will not be published. Required fields are marked *