0

I am trying to create a chat app using react vite and firebase, i am using firestore to store and retrieve chats, i imported getFirestore from firebase/firestore, and passed it to the "db" constant but the app throws an error saying db.collection is not a function.

import React from "react";
import "./App.css";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { useCollectionData } from "react-firebase-hooks/firestore";
import {
  getAuth,
  GoogleAuthProvider,
  signInWithPopup,
  signOut,
} from "firebase/auth";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const ChatRoom = () => {
  const messagesRef = db.collection('messages'); //this is where the error occurs

  const [user] = useAuthState(auth);
  return (
    <div>
      <h1>Chat Room</h1>
      <p>Welcome {user.displayName}</p>
      <button onClick={LogOut}>Sign Out</button>
    </div>

2 Answers 2

1

You have to import collection from firebase/firestore and using getDocs we can get all documents in a collection.

FIRESTORE_DOC

import { collection, getDocs, query, limit } from 'firebase/firestore';
import { useEffect } from 'react';
import { db } from 'your_db_file';

function ChatRoom(){
    useEffect(async ()=>{
        function getMessages(){
            const colRef = collection(db,'messages');
            const qry = query(colRef,limit(25));
            const messages = await getDocs(qry);
        
            console.log(messages.docs);
            return messages.docs
        }
        const messages = await getMessages();
        // do things with message
    })
    ....
}

I've used query and limit so we can limit the data.

0

The way you're importing Firebase modules/methods/functions and initializing Firebase use web modular API, but your implementation to retrieve data from Firestore uses web namespaced API. The correct way to retrieve data from Firestore is the following:

import { doc, getDoc } from "firebase/firestore";

const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  // docSnap.data() will be undefined in this case
  console.log("No such document!");
}

See this documentation for your reference.

Not the answer you're looking for? Browse other questions tagged or ask your own question.