Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop not working with google cloud firestore in react native

I am trying to migrate from real-time database to firestore in react-native with expo. Why won't the foreach loop work now?

RTDB

firebase.database().ref('messages').child(this.chatID).on('value', snap => {
        let messages = []
        snap.forEach(message => {
            messages.push(message.val())
        })
        this.setState({messages: messages})
    })

Firestore

const unsubChat = firebase.firestore().collection('messages').doc(this.chatID).onSnapshot(docSnapshot => {    
        let messages = []
        const myMesgs = docSnapshot.data()
        if (docSnapshot.data()){
        myMesgs.forEach(message => {
            console.log(message)
        })
        }
    })

snap and myMesgs are identical objects. I get a function undefined error when trying to use .foreach on myMesgs. I want to push the value of each object inside myMesgs into an array.

enter image description here

like image 693
Tipper Avatar asked Aug 21 '26 20:08

Tipper


1 Answers

Change this:

 myMesgs.forEach(message => {
        console.log(message)
    })

to this:

docSnapshot.forEach(message => {
        console.log(message)
    })

more info here: https://firebase.google.com/docs/firestore/query-data/listen

like image 193
Peter Haddad Avatar answered Aug 24 '26 14:08

Peter Haddad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!