How do I get firestore documents with a where() and count it?

In what I’ve done, users will select according to what they want.

the selected variable here store the value of what the user has selected. I could already get the value of the selected here.

Below are my codes:

  const [size, setSize] = useState(0)

  const getData = async () => {
    const citiesRef = firestore.collection("users");
    const snapshot = await citiesRef
      .where("item.itemName", "==", selected)
      .get();
    snapshot.forEach((doc) => {
      setSize(doc.data());
    });
  };

  useEffect(() => {
    getData();
  }, []);

  console.log(size.length)

Currently, if I’ll console.log(size) or console.log(doc.data()), it won’t display anything. Any help would be appreciated. Thank you.

Answer

You can use size property to check number of documents in the querySnapshot.

const [size, setSize] = useState(0)

const getData = async () => {
  const citiesRef = firestore.collection("users");
  const snapshot = await citiesRef
    .where("item.itemName", "==", selected)
    .get();
  setSize(snapshot.size)
};