Ad

How Can My App Wait For A Write Execution By A Cloud Functions In Firebase Before Continuing?

I have a cloud function that creates my custom user object in the data base once a new user has registered. Meanwhile in the app itself, after a user is registered, they are transferred to the main page.

The problem is, that the first executed function in the main page (crucial) is getting the user object, because it is needed for any action in the app. But because the page opened before the cloud function has created this user object, when the function in the main page tries to get that object it doesn't exist yet.

The result of that is that as soon as the user clicks anything pretty much, they are sent back to the register page. The register activity recognizes that they are actually logged in, send them back to the main page, and at that point everything would work as the object has been created, but the experience for the user isn't great and it feels like an error.

How can I prevent that? What's the simplest thing I can implement in my register activity, that would wait for some signal from the cloud function that the object has been created, before sending the user to the main page?

Ad

Answer

You can instruct your app to listen on the document that it expects to be created, using a DocumentReference onSnapshot or whatever is the equivalent for your client platform. The obvious requirement is that your app knows the exact path of the document that the function is going to create. In your case, it sounds like the client can know based on the user's UID assigned by Firebase Authentication.

If your app can't identify that document that's expected to be created by the function, then the function is going to have to tell the client. If it's an HTTP type function, the client should receive this document ID in the response. If it's not an HTTP type function, then you'll need to find yet another way to inform the client of what it's waiting on.

In any event, the onSnapshot callback will be triggered when the document is created, and you can use that to determine when to allow the user to proceed. You should of course remove the listener from that DocumentReference when you're done.

Ad
source: stackoverflow.com
Ad