0

When I run checkDoc I'm finding that my State validDoc will initially be set to false, but the second time I run it the value returns true. I know the document I'm querying for is present. I'm not sure what I'm doing wrong.

class PropertiesViewModel: ObservableObject {

    @Published var validDoc= false

    private var db = Firestore.firestore()

    func checkDoc(docRef: String) -> Bool {

        db.collection(docRef).getDocuments { (querySnapshot, error) in
                if querySnapshot?.count ?? 0 > 0 {
                    self.validDoc = true
                }
        }
        print("validDoc \(validDoc)")
        return validDoc
    }
}

Here's my return

validLogin false
validLogin true
Robert
  • 809
  • 3
  • 10
  • 19

1 Answers1

1

The only thing that's wrong is your expectations about how getDocuments works.

getDocuments is asynchronous, and the callback (completion) you pass to it is executed after it returns. Print something in the callback and it'll be more clear what's actually going on.

Given that, checkDoc cannot possibly return the correct value synchronously unless you do something to make it block (which you should not do). You will need to handle all query results asynchronously.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441