codekh
codekh

Reputation: 45

React Native: How can i retrieve a firebase firestore document as an array?

I have the following code. How can it be rectified to return an array as an object?

firebase.firestore().collection('users').get().then((querySnapshot)=>{              
        
          let items = Object.values(querySnapshot);
           this.setState({items});
        console.log(items)

});

This is my Database Firebase Firestore Database Snapshot

The following appears in the console and isn't friendly to retrieve data from it

  Array [
      No {
        "Ad": Ti {
          "$o": true,
          "Co": false,
          "Do": Array [],
          "Fo": Array [],
          "Mo": [Function anonymous],
          "No": null,
          "So": Promise {
            "_40": 0,
            "_55": Promise {
              "_40": 0,
              "_55": null,
.........

How can i return this in the console

Array [
  Object {
    "imageUrl2": "https://firebasestorage.googleapis.com/v0/b/bnv1-16406.appspot.com/o/images%2FTue%20Sep%2001%202020%2020%3A19%3A39%20GMT%2B0300%20(EAT)?alt=media&token=b9d1a38e-26a2-4d93-af2e-aded4747fff1",
    "shopName": "Buule Mohammed",
    "statuz": "seller",
  },
]

Upvotes: 1

Views: 1454

Answers (2)

FredAstaire
FredAstaire

Reputation: 351

I would do the following:

firebase.firestore().collection('users').get().then((querySnapshot)=>{              
  const objectsArray = [];
  querySnapshot.forEach((user) => {
    objectsArray.push(user.data());
  });
  console.log(objectsArray);
});

Upvotes: 2

user11202780
user11202780

Reputation:

For get data from firestore the method is: 

     const dbRef = firebase.firestore().collection('users').get();
        const user = dbRef.subscribe(o => {
                  o.forEach(u => {
                     console.log(u.data());
                   }              
                })
        });

another method is:
const userRef = this.db.collection('users').valueChanges();
    userRef.subscribe(k => {
      k.forEach(u => {
        console.log(u)
      })
    })

and if you want more data you need create something lik this: 

    ngOnInit(): void {
        this.getUser().subscribe(u => {
          console.log(u);
        })
      }

and method: 

    getUser = () => {
        return this.db.collection('users').snapshotChanges().pipe(
          map(action => action.map(a => {
            const id = a.payload.doc.id;
            const data = a.payload.doc.data() as User
            return {id, ...data}
          }))
        )
      }

Upvotes: 0

Related Questions