Home > Software engineering >  Is it possible to add a method dynamically in Javascript?
Is it possible to add a method dynamically in Javascript?

Time:10-05

Hey I am making a firebase database call that looks like this:

db.collection("posts").where("location", "==", location)
    .get().then((querySnapshot) => {
        [...]
    })

The user can specify from what countries he would like to get posts (the .where() method is for that). But he can also pick all the countries, so in that case the method is no longer needed. Is there a way to add methods dynamically?

Something like this:

db.collection("posts")if(location != "all"){.where("location", "==", location)}
    .get().then((querySnapshot) => {
        [...]
    })

CodePudding user response:

You can use a function

const addLocationCondition = (collection, location) => 
    location === "all" ? collection : collection.where('location', '==', location);

addLocationCondition(db.collection('posts'), location).get()...

CodePudding user response:

No, you can't put a conditional there.

Just use if to decide whether to call .where().

let posts = db.collection("posts");
let filtered;
if (location == "all") {
    filtered = posts;
} else {
    filtered = posts.where("location", "==", location);
}
filtered.get().then(querySnapshot => { 
    // ...
});

CodePudding user response:

I'm not completely sure about this db API but this should work:

let query = db.collection("posts")
if(location != "all"){
  query = query.where("location", "==", location)
}
query.get().then((querySnapshot) => {
   [...]
})
  • Related