I am trying to set something up in my application so that I can detect if two users are editing the same document at the same time. The best way I could think to do this was by sending information to the backend when a user logs in and logs out, and checking that when I want to see if two users are active at the same time. Starting the application is easy to detect with useEffect, but I'm having trouble finding a way to do so cleanly.
I looked at the onunload and onbeforeunload, but those don't seem to have universal browser support, and I'd prefer to not disrupt the user experience with a popup. I was thinking about checking for idle, but if there's a cleaner method, such as something with Google Cloud Platform, that would be helpful. Thanks!
That sounds like a great use case for onDisconnect. You can read more about it here and here.
This would be a simple example:
var ref = firebase.database().ref("onlineState");
ref.onDisconnect().set(false);
What happens here is that this command is send to Firebase and lives there. When you lose connection to Firebase it will be executed. It doesn't matter if it's done by closing the browser/tab etc...
If you need a more complex code execution then attach a firebase cloud function trigger to those changes. It's importand to know that you can't execute client side code on that event.