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
You have to import
collection
fromfirebase/firestore
and usinggetDocs
we can get all documents in a collection.FIRESTORE_DOC
I’ve used
query
andlimit
so we can limit the data.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:
See this documentation for your reference.