I'll try to explain myself the best I can.
What I'm trying to do is to set a common function which I can pass the name of the collection and do something with that. The problem is that since it is an asynchronous request I can't just do var a = getFirestoreData();
so i'll have to use this piece of code over and over again:
const db = firebase.firestore();
myCollection = 'SomeRandomCollectionName';
//Repetitive piece of code
db.collection(myCollection).get().then((snapshot) => {
var dataFromCollection = [];
snapshot.docs.forEach(doc => {
dataFromCollection.push(doc.data());
})
//TODO -> Do something with that data.
});
I want to be able to do different things with different collections with that same function (only one collection each time).
Basically what I want is something like a Utils class and use it for example:
Utils.getUsers("users");
Utils.getUsersAndUpdate("users", fieldToUpdate, dataToInsert);
Both of those functions use that same previous piece of code but with different continuity. How do I do this taking into account that it is an asynchronous request?
This is kind of a solution I made but it lacks the possibility to add parameters to the targetFunction
since the amount of parameters each function takes may vary.
function getFromDatabaseToFunction(targetFunction, collection){
db.collection(collection).get().then((snapshot) => {
var dataToTargetFunction = [];
snapshot.docs.forEach(doc => {
dataToTargetFunction.push(doc.data());
})
targetFunction(dataToTargetFunction);
})
}
P.S. This may likely be a duplicate but since I don't know what to search for I can't say for sure
from Firebase Firestore - Common function for queries but with different outcomes
No comments:
Post a Comment