invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.63k stars 2.2k forks source link

[🐛] 🔥 TypeError: this._firestore.native.documentGet is not a function (it is undefined) #7991

Closed michelletwain closed 2 weeks ago

michelletwain commented 2 weeks ago

Issue

I'm trying to implement a "recommended friends" feature, and users have "following" and "followers" lists in firestore database. For some reason I keep running into this TypeError saying that the function I'm using is not a function.

simulator_screenshot_750A3900-4114-4612-B928-E6D944A73E35

This is the code snippet for the screen where this issue is happening:

import React, { useState, useEffect } from 'react';
import { SafeAreaView, StyleSheet, Text, View, TouchableOpacity, ScrollView, TextInput, Alert } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import firestore from '@react-native-firebase/firestore';

type Friend = {
    id: string;
    name: string;
    username: string;
};

function PeopleQuickAddScreen({ route, navigation }) {
    const params = route.params;
    const [currentTab, setCurrentTab] = useState('Quick Add');
    const [recommendedFriends, setRecommendedFriends] = useState<Friend[]>([]);
    const [visibleFriendsCount, setVisibleFriendsCount] = useState(3);
    const [friendsError, setFriendsError] = useState<string | null>(null);

    useEffect(() => {
        fetchRecommendedFriends();
    }, []);

    const fetchRecommendedFriends = async () => {
        try {
            const userRef = firestore().collection('users').doc(params.userId);
            const userSnapshot = await userRef.get();

            if (!userSnapshot.exists) {
                setFriendsError('User not found.');
                return;
            }

            // Get the university from route params
            const userUniversity = params.university;

            // Get the list of user IDs the current user is following
            const followingSnapshot = await userRef.collection('following').get();
            const followingIds = followingSnapshot.docs.map(doc => doc.id);

            // Query all users from the same university excluding the current user and those already followed
            const usersSnapshot = await firestore()
                .collection('users')
                .where('university', '==', userUniversity)
                .get();

            const friends = usersSnapshot.docs
                .filter(doc => doc.id !== params.userId && !followingIds.includes(doc.id))
                .map(doc => {
                    const data = doc.data();
                    return {
                        id: doc.id,
                        name: data.name || 'No Name',   // Default to 'No Name' if undefined
                        username: data.username || 'Unknown', // Default to 'Unknown' if undefined
                    };
                }) as Friend[];

            // Set recommended friends to be displayed
            setRecommendedFriends(friends.slice(0, 10)); // Example to show first 10 recommendations
            setFriendsError(null);
        } catch (error) {
            console.error('Error fetching recommended friends:', error);
            setFriendsError('No friends to recommend, invite some to join CampusWatch!');
        }
    };

What my FireStore databse looks like:

Screenshot 2024-08-26 at 5 42 09 PM

So, it's for some reason not able to use the get function, but I'm not sure why. I've tried reinstalling pods, I tried making files to test FireStore with, but nothing is working. I used FireBase Authentication and it worked fine, so I'm not sure why I'm having so much trouble with FireStore.

I tried asking ChatGPT and I was told to make a firebaseConfig.js. Not sure if it did anything (obviously replaced with my own keys and stuff):

'firebaseConfig.js:

// firebaseConfig.js
import firebase from '@react-native-firebase/app';

const firebaseConfig = {
  apiKey: "MY_API_KEY",
  authDomain: "MY_AUTHDOMAIN",
  projectId: "MY_PROJECTID",
  storageBucket: "STORAGEBUCKET",
  messagingSenderId: "SENDERID",
  appId: "APPID",
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} else {
  firebase.app(); // if already initialized, use that one
}

export default firebase;

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "CampusWatch", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint .", "start": "react-native start", "test": "jest" }, "dependencies": { "@react-native-async-storage/async-storage": "^1.24.0", "@react-native-firebase/app": "^20.4.0", "@react-native-firebase/auth": "^20.4.0", "@react-native-firebase/firestore": "^20.4.0", "@react-native-picker/picker": "^2.7.7", "@react-navigation/native": "^6.1.18", "@react-navigation/native-stack": "^6.11.0", "axios": "^1.7.4", "react": "18.3.1", "react-native": "^0.75.2", "react-native-maps": "^1.18.0", "react-native-safe-area-context": "^4.10.9", "react-native-screens": "^3.34.0", "react-native-vector-icons": "^10.1.0" }, "devDependencies": { "@babel/core": "^7.20.0", "@babel/preset-env": "^7.20.0", "@babel/runtime": "^7.20.0", "@react-native/babel-preset": "0.75.2", "@react-native/eslint-config": "0.75.2", "@react-native/metro-config": "0.75.2", "@react-native/typescript-config": "0.75.2", "@types/react": "^18.3.4", "@types/react-native": "^0.73.0", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.6.3", "eslint": "^8.19.0", "jest": "^29.6.3", "prettier": "2.8.8", "react-test-renderer": "18.3.1", "typescript": "^5.0.4" }, "engines": { "node": ">=18" } } ``` #### `firebase.json` for react-native-firebase v6: I don't see a firebase.json already in my code

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, '13.4' require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' target 'CampusWatch' do # Use the standard React Native setup config = use_native_modules! use_frameworks! :linkage => :static use_react_native!( :path => config[:reactNativePath], :hermes_enabled => true ) pod 'React-RCTAppDelegate', :path => '../node_modules/react-native/Libraries/AppDelegate' pod 'React', :path => '../node_modules/react-native/' # Firebase and other dependencies with modular headers pod 'Firebase/Core', :modular_headers => true pod 'Firebase/Auth', :modular_headers => true pod 'Firebase/Firestore', :modular_headers => true pod 'FirebaseCoreExtension', :modular_headers => true pod 'FirebaseFirestoreInternal', :modular_headers => true pod 'GoogleUtilities', :modular_headers => true pod 'gRPC-C++', :modular_headers => true # Ensure you have the following lines to use Google Maps pod 'GoogleMaps' pod 'Google-Maps-iOS-Utils' pod 'react-native-maps', :path => '../node_modules/react-native-maps', :modular_headers => true pod 'react-native-google-maps', :path => '../node_modules/react-native-maps' pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons' pod 'RNFBApp', :path => '../node_modules/@react-native-firebase/app' pod 'RNFBFirestore', :path => '../node_modules/@react-native-firebase/firestore' target 'CampusWatchTests' do inherit! :complete # Pods for testing end post_install do |installer| react_native_post_install(installer) installer.pods_project.build_configurations.each do |config| config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64' end end end ``` #### `AppDelegate.m`: ```objc #import "AppDelegate.h" #import #import #import // Add this import #import // Add this import #import "RCTBridgeDelegate.h" // Add this import #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Initialize Firebase [FIRApp configure]; [GMSServices provideAPIKey:@"MYAPI"]; RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"CampusWatch" initialProperties:nil]; rootView.backgroundColor = [UIColor whiteColor]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; #else return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } @end ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // N/A ``` #### `android/app/build.gradle`: ```groovy // N/A ``` #### `android/settings.gradle`: ```groovy // N/A ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: macOS 14.6.1 CPU: (12) arm64 Apple M2 Max Memory: 71.75 MB / 32.00 GB Shell: version: "5.9" path: /bin/zsh Binaries: Node: version: 20.16.0 path: /usr/local/bin/node Yarn: Not Found npm: version: 10.8.1 path: /usr/local/bin/npm Watchman: version: 2024.08.12.00 path: /opt/homebrew/bin/watchman Managers: CocoaPods: version: 1.15.2 path: /opt/homebrew/lib/ruby/gems/3.3.0/bin/pod SDKs: iOS SDK: Platforms: - DriverKit 23.5 - iOS 17.5 - macOS 14.5 - tvOS 17.5 - visionOS 1.2 - watchOS 10.5 Android SDK: Not Found IDEs: Android Studio: Not Found Xcode: version: 15.4/15F31d path: /usr/bin/xcodebuild Languages: Java: Not Found Ruby: version: 2.6.10 path: /usr/bin/ruby npmPackages: "@react-native-community/cli": Not Found react: installed: 18.3.1 wanted: 18.3.1 react-native: installed: 0.75.2 wanted: ^0.75.2 react-native-macos: Not Found npmGlobalPackages: "*react-native*": Not Found Android: hermesEnabled: true newArchEnabled: false iOS: hermesEnabled: true newArchEnabled: false ``` - **Platform that you're experiencing the issue on**: - [x] iOS - [ ] Android - [x] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `e.g. 5.4.3` - 20.4.0 - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - FireStore - **Are you using `TypeScript`?** - `Y/N` & `VERSION` - Y 5.0.4


russellwheatley commented 2 weeks ago

@michelletwain - does your iOS project have a GoogleService-Info.plist configuration file? Here is the documentation for iOS setup.

michelletwain commented 2 weeks ago

@michelletwain - does your iOS project have a GoogleService-Info.plist configuration file? Here is the documentation for iOS setup.

@russellwheatley yeah my iOS project has that file. I followed the steps on that page and Firebase Authorization/Authentication works fine on my app, and my app is able to upload to the Firestore database. It just can't use the get function for Firestore database documents, but I'm not sure why

michelletwain commented 2 weeks ago

Got it to work by importing my db from firebaseConfig.js (which I had to make myself)