TheDevZak
TheDevZak

Reputation: 1

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

Hi i have this code i have using firebase v9 web. here is my code:

 const [post, setPosts] = useState([]);

  useEffect(() => {
    const q = query(collection(db, "posts"));

    onSnapshot(q, (querySnapshot) => {
      setPosts(
        querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
    });
  });

Upvotes: 0

Views: 3976

Answers (2)

Marcel Hoekstra
Marcel Hoekstra

Reputation: 1488

I used to create the firebaseApp which I could use later on in the application. Since firebase@9 I got the same error. Now i create the firebaseApp before the database call which seems to work.

const [post, setPosts] = useState([]);

useEffect(() => {
    const app = initializeApp(firebaseOption);
    const db = getFirestore(app);
    const q = query(collection(db, "posts"));

    onSnapshot(q, (querySnapshot) => {
      setPosts(
        querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
    });
  });

Upvotes: 1

Dharmaraj
Dharmaraj

Reputation: 50830

The documentation has examples of both V8 name-spaced and V9 modular syntax:

import { getFirestore, collection, query, where, onSnapshot } from "firebase/firestore";

const db = getFirestore()

const q = query(collection(db, "posts"));

const unsubscribe = onSnapshot(q, (querySnapshot) => {
  setPosts(querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })))
});

Upvotes: 2

Related Questions