简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'onSnapshot')

Im am trying to collect data from firebase database but get the error 'TypeError: Cannot read properties of undefined (reading 'onSnapshot')'

Feed.js

    const Feed = ({profilePic, message, timestamp, username, image}) => {
    const [posts, setPosts]  =useState([]);
    //realtime database connection
     useEffect(() => {
     db.collection['posts'].onSnapshot(snapshot => (
    setPosts(snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })))
   ));
    }, []);

   return (

Firebase.js

  import firebase from 'firebase/compat/app';
  import 'firebase/compat/firestore';

 //initialize Firebase
  firebase.initializeApp(firebaseConfig);

 //database
 const db = firebase.firestore();
 export default db;

The collection is a method, not an array. So:

db.collection('posts').onSnapshot(...
          // 👆      👆

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM