Manager09
Manager09

Reputation: 21

React Firestore query doesn't return found document on first run

I'm building a web app, where users can make appointments with doctors and I want to prevent a user to make an appointment at the same time and date with the same doctor that a different user has already requested. I'm using a firestore database to store the appointments as documents. This is my function, which handles the check and pushes to my firebase database:

    const addAppointment = async (date: Date | null, speciality: string | undefined) => {
      const appointmentsRef = collection(db, "appointments");
      const q = query(appointmentsRef, where("speciality", "==", speciality), where("date", "==", date))
      const docs = await getDocs(q);
      docs.forEach((doc: any) => {
        console.log(doc.data())
      })
      console.log(docs.docs.length)
      if (docs.docs.length === 0) {
        try{
          await addDoc(collection(db, "appointments"), {
            email: auth.currentUser?.email,
            date,
            speciality
          });}
          catch (err) {
            console.error(err);
          }
        return false
      }
        return true
    };

On page refresh, if I try to make an appointment that has already been requested, the docs length is 0 and I can make the same appointment. However, If I try again (without refreshing), the doc length is 1 and nothing is pushed to the db.

Upvotes: 0

Views: 51

Answers (1)

Manager09
Manager09

Reputation: 21

I am now parsing the date field as string and I am essentially comparing strings and not dates.

Upvotes: 1

Related Questions