Ad

Render Array Data Gotten From Firebase Firestore

I am trying to get the data inside my messages array field from firestore, I can see the data in my debugger, but cannot fetch a single part of the message. I am roughly new to react native and firebase. kindly direct me. The image below is the data i want to fetch from my firestore database enter image description here

below is my sample code.

          const { currentUser } = Firebase.auth;
          const userUid = currentUser.uid;
          const chatroomMessages = [];

          const ref = await Firebase.firestore.collection('chatrooms');
          const getDoc = ref.doc(this.props.item.key)
                              .onSnapshot(doc => {
                                if (!doc.exists) {
                                  console.log('No such document!');
                                  return;
                                }
                                //const { createdAt } = change.data();

                               const messages = doc.data();

                               const data = messages.messages;

                               //const { ...text } = data;

                               chatroomMessages.push({
                                 data
                                 })

                               this.setState({
                                 chatroomMessages,
                                 });

                                    console.log('Document data:', chatroomMessages);
                              });
Ad

Answer

I was able to fix it by doing this

          _fetchChatData = async () => {
              this.unsubscribe = await this.newChatRef.doc(this.props.chatID)
              .onSnapshot(doc => {
                const data = doc.data().message;

                const privateMessages = [];
                for (const message in data) {
                  privateMessages.push({
                    text: data[message].text,
                    key: data[message].createdAt,
                    authorID: data[message].authorID,
                    author: data[message].author,
                    authorPic: data[message].authorPic,
                  });
                }

                this.setState({
                  privateMessages,
                });
                console.log(privateMessages);
              }
            );
          }
Ad
source: stackoverflow.com
Ad