Home > database >  How can i change this Firebase version 8 code to version 9
How can i change this Firebase version 8 code to version 9

Time:10-20

How to do this with Firebase version 9 Web SDK

db.collection('rooms')
 .doc(id)
 .collection('messages')
 .orderBy('timestamp', 'asc')
 .onSnapshot((snapshot) => 
   setState(snapshot.docs.map(doc => 
   doc.data()))
 )

CodePudding user response:

The following should do the trick:

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

const id = ...;

const messagesColRef = collection(db, "rooms", id, "comments");
const messagesQuery = query(messagesColRef, orderBy("timestamp"));
onSnapshot(messagesQuery, (snapshot) => {
   setState(snapshot.docs.map(doc => 
   doc.data()))
});

Have a look at the Firestore reference.

  • Related