FIREBASE getting document data

Tags: , , , ,



I’m making an app and trying to get product data by it’s id inside a modal in ionic 4. I’m using typescript to do it but without luck. Because de calls to firebase are asynchronous i cannot get the data that is held in firebase and also because i’m new to subject i cannot figured out the proper way to write the code. I read about how to do it but i’m having a hard time to achieve it.

Here is my function that tries to grab product data from firebase. It always logs empty on console.log(‘todo’, todo).

async editProduct(id) {
        const getTodo = docRef => {
            setTimeout(() => {
                docRef = this.afs.collection("products").doc(id);
                docRef.get().subscribe((doc) => {
                    if (doc.exists) {
                        let data = doc.data();
                        return data;
                    } else {
                        console.log("No document.");
                        return false;
                    }
                });
            }, 2000)
        }

        getTodo(todo => {
            console.log('todo', todo)
        })

        const modal = await this.modalCtrl.create({
            component: AdminProductPage,
            'id': id,
        });
        await modal.present();
    }

Answer

There is something wrong with your “getTodo”. Probable you are logging empty data with your code, I can give you the proper functional example:

myData

editProduct() {
    this.afs.collection("products").doc(id)
        .valueChanges()
        .subscribe(data => {
          console.log(data)
          myData = data
        })
}

getData() {
    console.log(this.myData) // You will log it twice with this line
}

GOOGLE EXAMPLE

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});

https://firebase.google.com/docs/firestore/query-data/get-data?hl=es



Source: stackoverflow