javascriptgoogle-cloud-firestorerxfire

How to check that a document has been created in Firestore with RxFire


In my React app, I want to check whether a background firebase function has created the document in Firestore before updating my UI. So I use the docData function from RxFire to subscribe to changes in the specific, "about-to-be-created-from-a-background-function" doc:

const davidDocRef = db.doc('users/david');

// meantime, a firebase function creates "users/david" doc in the background 
// I am observing for changes to the firestore doc in my React Component:

useEffect(() => {
docData(davidDocRef,'uid').subscribe(userData => setUserId(userData.uid));
...

// I then check that orgId is not null by assuming that I will get back a doc.id after it has been created it in Firestore

The problem is that userData.uid always returns "david" regardless of the doc being created in Firestore. What am I doing wrong? It seems like it's returning the uid from the path I've set in the reference instead of an actual document path that has been (or should have been) created in firestore. When I change the reference to look for "users/foo" then userData.uid still returns "foo" instead of undefined or throughing an error.

In this case I can instead look for userData.name. This actually works as I get "undefined" if the document has not been stored in Firestore or "David" if it has, but I would expect the example above to work in a similar manner.


Solution

  • The value of the "uid" field is not going to change as it is the reference to the document.

    To confirm that the document was created, you should listen for changes in other fields, such as the name, as you already mentioned you do in your question.

    Additionally, the same creation/write operations will invoke intermediately the updates.