I am using the Firebase Stripe extension.
When a user is added to Firebase the Stripe extension uses Cloud Functions to create a users
document in the Firestore Datastore.
In my app I have a function that creates a Firebase user, and then tries to update the matching users
Firestore document.
But sometimes the Cloud Functions have not finished creating the users
document and it returns this error:
No document to update: projects/APP_NAME/databases/(default)/documents/users/KHaY21FSUasdfOXFS123Kfge85VA3
To get around this problem I am using a timeout
that pauses for a few seconds before proceeding. It's not an ideal solution.
Instead, I want to know if the Firebase Stripe extension has finished creating the users
doc before proceeding.
How can that be done?
Here is my app function:
export const useCreateUserWithEmailAndPasswordTask = () => {
const updateDocTask = useUpdateDocTask();
return useTask(function* (
signal,
email: string,
password: string,
firstName: string,
lastName: string,
) {
// Create the user in Firebase
// The Firebase Stripe extension will now use Cloud Functions to also create a 'users' doc with related user info
const userCredential: UserCredential = yield createUserWithEmailAndPassword(
auth,
email,
password
);
// Now I wait 3 seconds to make sure the 'users' doc is created before updating it.
// Without this timeout it will occasionally throw an error because updateDocTask is called before the 'users' doc is created
// Is there a better way of doing this?
yield timeout(3000);
const updateDoc: void = yield updateDocTask.perform(
'users',
userCredential.user.uid,
{
firstName: firstName,
lastName: lastName,
createdAt: timestamp,
}
);
return Promise.all([userCredential, updateDoc]);
});
};
CodePudding user response:
You can use realtime listeners instead of setTimeout()
as shown below:
import { doc, onSnapshot } from "firebase/firestore";
const unsub = onSnapshot(doc(db, "users", "<USER_DOC_ID>"), (doc) => {
// This function triggers whenever the document is created/updated/deleted
console.log("Data: ", doc.data());
});
Do check if doc.data()
has data already just in case the extension has added document before user reaches this page.