React Firestore query not finding document on first run
P粉463291248
P粉463291248 2023-09-12 10:49:36
0
1
700

I'm building a web application where users can make appointments with doctors and I want to prevent users from making appointments with the same doctor at the same time and date that other users have already requested. I'm using a firestore database to store appointment information as a document. Here is my function that handles the check and pushes it 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 book 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 it is not pushed to the database.

P粉463291248
P粉463291248

reply all(1)
P粉237029457

I am now parsing the date field as a string and actually comparing strings instead of dates.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template