Search code examples
javascripthtmlfirebasegoogle-cloud-firestoredropdownbox

Pass a variable into a query (Firebase)


this is really frustrating me I hope you kind people can assist me.

I have a firebase firestore db that stores info about properties and cities. All properties contain a key:value pair called location_city. It is a string that stores the City that the property resides in.

I have made a dropdown box on a webpage with a list of available cities. The idea is to dynamically display properties from the selected city, by means of the .where() method. The third parameter accepted by the method is the string you want to query against.

I want to pass the text value of the dropdown list into the query.

Here's my code:

let selectedCityViewHomes;

function getDropdownSelection(sel) {
  selectedCityViewHomes = sel.options[sel.selectedIndex].text;
  selectedCityViewHomes.toString();
}

db.collection('Homes')
  .where('location_city', '==', selectedCityViewHomes)
  .get()
  .then(snapshot => {
    snapshot.docs.forEach(doc => {
      renderHome(doc);
    });
  });

The query method only seems to work if you manually enter a string into the parameter and does not seem to allow you to pass a variable (which is a string) into the method.

I have tried concatenating "'" either side to mimic 'Manchester', for example and this did not work either.

TIA

Charlie


Solution

  • EDIT: I found where i had gone wrong, it was an issue of scope i think. I fixed it by creating a function which wrapped the db.collection code and passed in the variable as an argument.

    const updateHomesViewHomes = (input) => {
        db.collection('Homes').where('location_city', '==', input).get().then((snapshot) => {
            homesViewHomes.innerHTML = "";
            snapshot.docs.forEach(doc  => {
                renderHome(doc);
            });
        });
    };
    

    Thanks for the replies, hope this helps someone.