Perform simple queries in Cloud Firestore - how can i filter all through select?

62 Views Asked by At

I need to to filter data through queries from Firestore, but how can I also get all of them(in my case all states in firestore)? What should be useState value in this case? I'm a newbie :) Thank you for your help, I really appreciate it.

//WHAT useState VALUE SHOULD I USE TO GET ALL STATES IN DATABASE?
const (city, setCity) = useState("CA");

const citiesRef = collection(db, "cities");
const q = query(citiesRef, where("state", "==", city));

Tried to search in firestore docs and google.

2

There are 2 best solutions below

0
Prathmesh On

you need to use getDocs() method provided by firebase as follows

here, q is your query ( const q = query(collection(db, "cities"), where(....));

add following code -

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data())
});

you can refer to this link

1
Roopa M On

As you wanted to use useState, You can pass an empty string ” “ or Null value and use != instead of = operator in the where clause. And use getDocs() to retrieve all documents as mentioned by @Prathmesh

Here is the complete code:

const [city, setCity] = useState(" ");

const citiesRef = collection(db, "cities");
const q = query(citiesRef, where("state", "!=", city));

const querySnapshot = await getDocs(q);
querySnapshot.docs.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});