如何检查 Firebase Stripe 扩展是否已完成创建 customer/user 文档?

How to check if the Firebase Stripe extension has finished creating the customer/user document?

我正在使用 Firebase Stripe 扩展程序。

当用户添加到 Firebase 时,Stripe 扩展使用 Cloud Functions 在 Firestore 数据存储中创建一个 users 文档。

在我的应用程序中,我有一个创建 Firebase 用户的功能,然后尝试更新匹配的 users Firestore 文档。

但有时 Cloud Functions 尚未完成 users 文档的创建并且 returns 此错误:

No document to update: projects/APP_NAME/databases/(default)/documents/users/KHaY21FSUasdfOXFS123Kfge85VA3

为了解决这个问题,我使用了 timeout,它会在继续之前暂停几秒钟。这不是一个理想的解决方案。

相反,我想知道 Firebase Stripe 扩展程序在继续之前是否已完成创建 users 文档。

如何做到这一点?

这是我的应用程序功能:

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]);
  });
};

您可以使用 realtime listeners 代替 setTimeout(),如下所示:

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());
});

请检查 doc.data() 是否已有数据,以防扩展程序在用户到达此页面之前添加文档。