skip to Main Content

please can you help me to write this request in a new firebase notation please

useEffect(() => {
  let unsubscribe;
  if(postId){
    unsubscribe =db
    .collection("posts")
    .doc(postId)
    .colection("comments")
    .onSnapshot((snapshot)=>{
      setcomments(snapshot.doc.map((doc)=>doc.data()))
    })
  }
  
  
}, []);

best regards

im trying to write it but i dont how can i use "db.doc"
im writing somthing like that

useEffect(() => {
    onSnapshot(
      collection(db, "posts", "comments"),(snapshot) =>
        setcomments(
          snapshot.docs.map((doc) =>
            post: doc.data())
        )
    );
  }, []);

but it’s not work

3

Answers


  1. Chosen as BEST ANSWER

    thanks a lot my friend, but now, in my console, i have this error " Cannot access 'collection' before initialization" i show you my modification

    import { collection, onSnapshot } from "firebase/firestore";
    import { useState, useEffect } from 'react';
    import { db } from "./firebase";
    const [comments, setcomments] = useState([])
    
          useEffect(() => {
          
          if(postId){
            const collection = collection(db, "posts", postId, "comments");
            const unsubscribe = onSnapshot(collection, (snapshot) => {
              setcomments(snapshot.doc.map((doc) => doc.data()));
            });
          }
          return ()=>{
            unsubscribe()
          }
          
          
        }, [postId]);
    

  2. The following should do the trick:

    import { collection, onSnapshot } from "firebase/firestore";
    
    const collection = collection(db, "posts", postId, "comments");
    const unsubscribe = onSnapshot(collection, (snapshot) => {
      // ...
    });
    

    More details on how to declare sub-collections with the JS SDK v9 in this article.

    Login or Signup to reply.
  3. im fixed the probléme like that:

    import { collection, onSnapshot } from "firebase/firestore";
    import { useState, useEffect} from 'react';
    import { db } from "./firebase";
    
    
    const [comments, setcomments] = useState([])
     useEffect(() => {
      let unsubscribe
      if(postId){
    
        unsubscribe = onSnapshot(collection(db, "posts", postId, "comments"), (snapshot) => {
          setcomments(snapshot.doc.map((doc) => doc.data()));
        });
      }
      return ()=>{
        unsubscribe()
      }
      }, [postId]);
    

    but now i have this error: "Uncaught TypeError: Cannot read properties of undefined (reading ‘map’) at Array."
    please can you help me?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search