Home > Software design >  Can't get all document from collection firebase firestore
Can't get all document from collection firebase firestore

Time:01-12

I don't understand why I can't get data from firebase firestore database.

my error :

[FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore]

My config file with firebase config is correctly set, I can add Data with this model :

{ item: { ...event, date } }

My files structures : picture of my structure

I have correctly declared my state, I have async await with try catch.

I have used this from firebase documentation

EventList.js

import { FlatList, View, Text, StyleSheet } from "react-native";
import React, { useState, useEffect } from "react";
import { EVENTS_COLLECTION } from "../commons/constants";
import db from "../commons/services/firebase";

const EventList = () => {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    const fetchEvents = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, EVENTS_COLLECTION));
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
        });
        setEvents(
          querySnapshot.forEach((doc) => {
            doc.id, " => ", doc.data();
          })
        );
      } catch (error) {
        console.error(error);
      }
    };
    fetchEvents();
  }, [setEvents]);

  return (
    <View>
      <FlatList
        data={events}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View style={styles.eventContainer}>
            <Text style={styles.eventName}>{item.name}</Text>
            <Text style={styles.eventDate}>{item.date.toString()}</Text>
          </View>
        )}
      />
    </View>
  );
};
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL:
    "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

I try to get all documents from my events collection. My goal is to make an Calendar with event manager with firebase firestore database

when console.log(db) in EventList.js

WARN [2023-01-11T20:07:47.237Z] @firebase/firestore: Firestore (9.15.0): Connection WebChannel transport errored: {"defaultPrevented": false, "g": {"A": true, "J": null, "R": [Circular], "g": {"$": true, "$a": 5000, "A": 0, "B": null, "C": 0, "Ca": null, "D": "gsessionid", "Ea": -1, "F": [U], "Fa": 0, "G": 0, "Ga": false, "H": true, "Ia": [ud], "J": "", "K": undefined, "L": false, "M": true, "O": true, "P": false, "R": 0, "U": [Object], "V": -1, "W": 82724, "Y": "https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel", "aa": 0, "ab": false, "ba": false, "bb": false, "cb": 2, "eb": 2, "fb": 10000, "g": null, "h": [pd], "i": [Array], "j": [Sb], "l": [Z], "la": [Object], "m": null, "ma": undefined, "na": null, "o": null, "oa": null, "s": null, "sa": 0, "u": null, "ua": undefined, "v": null, "va": null, "wa": 600000}, "h": {"database": "projects/calendar-f3025/databases/(default)"}, "i": {"g": [Object], "h": 4, "src": [Circular]}, "j": {"g": [Circular]}, "l": "https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel", "o": undefined, "s": false, "v": true}, "status": 1, "target": {"A": true, "J": null, "R": [Circular], "g": {"$": true, "$a": 5000, "A": 0, "B": null, "C": 0, "Ca": null, "D": "gsessionid", "Ea": -1, "F": [U], "Fa": 0, "G": 0, "Ga": false, "H": true, "Ia": [ud], "J": "", "K": undefined, "L": false, "M": true, "O": true, "P": false, "R": 0, "U": [Object], "V": -1, "W": 82724, "Y": "https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel", "aa": 0, "ab": false, "ba": false, "bb": false, "cb": 2, "eb": 2, "fb": 10000, "g": null, "h": [pd], "i": [Array], "j": [Sb], "l": [Z], "la": [Object], "m": null, "ma": undefined, "na": null, "o": null, "oa": null, "s": null, "sa": 0, "u": null, "ua": undefined, "v": null, "va": null, "wa": 600000}, "h": {"database": "projects/calendar-f3025/databases/(default)"}, "i": {"g": [Object], "h": 4, "src": [Circular]}, "j": {"g": [Circular]}, "l": "https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel", "o": undefined, "s": false, "v": true}, "type": "c"}

CodePudding user response:

In firebase.js you export db like this:

export const db = getFirestore(app);

This is a named export, therefore you will need a named import:

import { db } from '../commons/services/firebase'
// or
// import * as config from '../commons/services/firebase'
// const db = config.db

The way you import is for default exports and results in your case with undefined. Therefore firebase complains that the first argument to collection is not correct (it's undefined).

You can read more about imports here.

CodePudding user response:

Try this one if EVENTS_COLLECTION returns the name of the collection correctly then you will get all documents otherwise use "Collection Name" where you write EVENTS_COLLECTION.

const fetchEvents= async () => { 
     await db.collection(EVENTS_COLLECTION).onSnapshot({
          error: e => console.error(e),
          next: (querySnapshot) => {
               var data = [];
               var i = 0;
               querySnapshot.forEach(doc => {
                    data.push(doc.data());
                    console.log(doc.id, " => ", doc.data());
               });
               setEvents(data)
          },
     })   
};
  • Related