How to create user and upload data on Firebase in one single transaction

firebase realtime database
transaction firebase android
firebase multiple transactions
firebase transaction example
firebase realtime database batch write
firebase batch query
firebase realtime database transaction
firebase save data android

I am making a web application which creates a user on Firebase using email and password firebase.auth().createUserUsingEmailAndPassowrd()

After the account is created, I immediately upload some data based on the forms values on the firebase database.

All works well, but sometimes, In worst case scenarios, the user is created but due to network issues the data is not uploaded. And the app is already redirected to a place where it needs that data and the whole app fails.

How can I make it certain that the user account is created only if the data I am trying to upload on database gets updated too.

Summary : Make sure that some data is uploaded along with user creation or the user doesn't get created at all.

Because you're so afraid of worst case scenario (which is absolutely normal), here is one way to do it: Consider you have these fields: email, password, and address. The address field is the one you need to store in your database (with user uid, of course).

First you try to register the user, and like Faizy said, you use onCompleteListener like this

mAuth.createUserWithEmailAndPassword(email, password)
    .onCompleteListener(... {
        ... onComplete (... task) {
            if (task.isSuccessful()) {
                doInsertTheData();
            }
...

When task is successful, then you want to insert the data into database, which doInsertTheData() is created for

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

And there you go, as long as the database saving process failed, the user credential will be deleted

Note: I actually have another method in mind when I type this, but it's too complicated and I think this one is more easy to understand (I haven't try/use this though)

Saving Data, transaction, Use transactions when working with complex data that could be corrupted by concurrent updates Import Admin SDK var admin = require("​firebase-admin"); // Get a First, create a database reference to your user data. Given a single key path like alanisawesome , only the data at the first  Select your CSV file. Make sure you have selected Hash as Output option. Press Convert button below, now you will able to see your JSON data, download the file. Step 2: Download service key from

Import Users, Ability to migrate existing or create new OAuth users (Google, Facebook, etc). Ability to Up to 1000 users can be imported in a single API call. Using the Cloud Firestore client libraries, you can group multiple operations into a single transaction. Transactions are useful when you want to update a field's value based on its current value, or the value of some other field.

You can do it in your OnComplete method of createUserUsingEmailAndPassowrd().

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

              if (task.isSuccessful()) {
                   //Create your user in DB here

                }
            }
        });

Build an Android App Using Firebase and the App Engine Flexible , When a new user logs into Playchat, the app requests a logging servlet for The servlet uses a Firebase transaction to guarantee that it is the only servlet Build an Android app, Playchat, that stores data in the Firebase Realtime Database. identifier doesn't change; your local server spins up a single servlet instance. First, create a database reference to your user data. Then use set () / setValue () to save a user object to the database with the user's username, full name, and birthday. You can pass set a string, number, boolean, null, array or any JSON object. Passing null will remove the data at the specified location.

If you need user to have certain data to use app, then might have to always check.. when they sign in:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // ... access ref to userData field(s) you care about..
    someUserFieldRef.once('value').then(snap => {
      if (! snap.exists()) {
        // redirect to setup page to add missing data..
      }
    })

  }
})

If they can use other parts of app, then you can defer check to when specific user data is necessary, get currentUser, then check for data..

Lessons learnt (the hard way) using Firebase RealTime Database, When a new user installs your App, you don't want him to be bothered by a login flow, don't have to create a new Firebase User but, link the provided credentials to your existing List<BusFavorite>)fun retrieveBusFavorites(): Single<List<BusFavorite>>} Uploading data to the cloud is completely free. Every client connected to a Firebase database maintains its own internal version of any active data. When data is written, it's written to this local version first. The Firebase client then synchronizes that data with the remote database servers and with other clients on a "best-effort" basis.

Firebase for Flutter - Codelabs, 1. Prerequisites. If you're familiar with object-oriented programming concepts, mobile programming, or Firebase; although completing an introductory Flutter  Transactional data is used when you need to return some data from the database then make some calculation with it and store it back. Let us say we have one player inside our player list. We want to retrieve property, add one year of age and return it back to Firebase. The amandaRef is retrieving the

Realtime Database, Creating a reference does not result in a request to your Database. Database Snapshots are immutable copies of the data at a Firebase Database update it to the recent activity feed and the posting user's activity feed using code like this: at a location using a placeholder value which is an object with a single .sv key. Learn how to maintain user/data relationships with Firebase users and data from the Realtime database. I provide three different methods for commonly encountered scenarios. Category

Audiences - Firebase Help, After you create an audience, it accumulates users who meet the be met: across all sessions, in a single session, or in a single event. the last 30 days (​assuming you have at least 30 days of data). For example, the Users who completed a transaction audience is defined as follows:. Visit your Google Cloud API Console and select the project that matches up with the Firebase project that you just created. Notice the project selection dropdown at the top-right edge of the console. Open the Credentials tab and click Create credentials. You want the API key option. Create a server key.

Comments
  • Good work! This is what I'd call a more resilient client. But you'd still have inconsistency if the client app crashes between the completion of the creation of the user and it writing to the database. To further reduce chances of that, I'd move this code into Cloud Functions trigger of the user creation: firebase.google.com/docs/functions/auth-events
  • @FrankvanPuffelen How does the cloud function trigger have access to the data needed to populate user record? ("address, ...")
  • Does anybody know if cross-feature transactions are going to be supported in the future?
  • While it's hard to say what will happen in the future, nobody is actively working on this at the moment.
  • is it possible that the user gets created and immediately i loose the connection (extreme paranoid) and the onComplete method fails. So i am left with the created user only. and not the data inside the db.