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
  • 14,486
  • 4
  • 43
  • 54
Spandan Manna
  • 37
  • 1
  • 6

1 Answers1

2

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
  • 29,469
  • 5
  • 26
  • 55
  • 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. – Spandan Manna May 01 '22 at 14:44