如何在单个事务中创建用户并在 Firebase 上上传数据

Pra*_*rma 4 android firebase react-native firebase-authentication firebase-realtime-database

我正在制作一个 Web 应用程序,它使用电子邮件和密码firebase.auth().createUserUsingEmailAndPassowrd()在 Firebase 上创建一个用户

创建帐户后,我立即根据 firebase 数据库上的表单值上传一些数据。

一切正常,但有时,在最坏的情况下,用户已创建,但由于网络问题,数据未上传。并且该应用程序已经被重定向到需要该数据的地方,并且整个应用程序都失败了。

我如何确保只有当我尝试上传到数据库的数据也更新时才创建用户帐户。

摘要:确保一些数据与用户创建一起上传,否则用户根本不会被创建。

koc*_*eng 5

因为您非常害怕最坏的情况(这绝对是正常的),所以有一种方法可以做到:考虑您有以下字段:电子邮件、密码和地址。地址字段是您需要存储在数据库中的字段(当然是用户 uid)。

首先你尝试注册用户,就像Faizy 说的,你onCompleteListener像这样使用

mAuth.createUserWithEmailAndPassword(email, password)
    .onCompleteListener(... {
        ... onComplete (... task) {
            if (task.isSuccessful()) {
                doInsertTheData();
            }
...
Run Code Online (Sandbox Code Playgroud)

当任务成功时,您想将数据插入到数据库中,该数据库doInsertTheData()是为

private void doInsertTheData() {
     // I believe you familiar with Firebase database inserting method, so I skip the long part
     FirebaseDatabase...setValue(address, new CompletionListener() {
         ... onComplete(FirebaseError firebaseError, ...) {
             if (firebaseError == null) {
                 // if your code reach here, its a happy ending
             } else {
                 // if it reach here, then you can remove the signed in user
                 // and tell the user that their registration is failed and should try again
                 FirebaseAuth.getInstance().getCurrentUser().delete();
             }
Run Code Online (Sandbox Code Playgroud)

好了,只要数据库保存过程失败,用户凭据就会被删除

注意:当我输入这个时,我实际上有另一种方法,但它太复杂了,我认为这个更容易理解(虽然我没有尝试/使用这个)