0

I want to change this Firebase V8 code to Firebase V9. I have tried to change this code to v9 in several ways, but unfortunately, all of them were failure:

useEffect(() => {
    const unsubscribe = db.collection("chats").onSnapshot((snapshot) => {
    setChats(
        snapshot.docs.map((doc)=>({
            id:doc.id,
            data: doc.data(),
           }))
        )
    );

    return unsubscribe;
}, [])
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Also just to confirm, what is value of `db` in this code? It must be Firestore instance initialized by `getFirestore()` function. – Dharmaraj Apr 30 '22 at 17:09
  • I have initialized db in a file called `firebase.js`. In firebase.js it has been initialized with the 'getFirestore()' function. –  May 01 '22 at 04:29
  • Have you tried refactoring the code as in my answer below? – Dharmaraj May 01 '22 at 04:30

1 Answers1

1

The collection() and onSnapshot() are top-level functions in Firebase v9 SDK that can be directly imported from Firestore SDK. Try refactoring the code as shown below:

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

useEffect(() => {
  const colRef = collection(db, "chats")

  onSnapshot(colRef, (snapshot) => {
    setChats(
      snapshot.docs.map((doc) => ({
        id: doc.id,
        data: doc.data(),
      }))
    )
  });

  return unsubscribe;
}, [])

Also checkout: Firestore: What's the pattern for adding new data in Web v9?

The documentation has examples of code written in both V8 and V9 syntax so you can just switch the tabs to Version 9 (Modular) and compare it with previous Version 8 (namespaced) syntax.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • I guess the logic is ok.. The problem is how to pass the data inside the array into a component? ```{chats.map(({ id, data: { chatName }}) => ( ))}``` \n but there is no chatName appearing on the screen. –  May 01 '22 at 14:44