khaled
khaled

Reputation: 53

How do I delete data from Firebase Realtime Database when a client loses connection

I am working on a game connect two players with firebase realtime databsee. but I want a way to can delete player data if lose his connection with the Internet.

Upvotes: 0

Views: 939

Answers (1)

user10747134
user10747134

Reputation:

This can be updated via the OnDisconnect method.

This original answer from Frank originally describes more details on the OnDisconnect method.

Read more about the interface here.

You can set up a "connected presence" with this Firebase example that uses the Realtime Database and Cloud Functions with OnDisconnect to show the status of a user. Pulled from the example:

var userStatusDatabaseRef = firebase.database().ref('/status/' + uid);

firebase.database().ref('.info/connected').on('value', function(snapshot) {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()'
    // method to add a set which will only trigger once this
    // client has disconnected by closing the app,
    // losing internet, or any other means.
    userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect()
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as 'online' knowing that the
        // server will mark us as offline once we lose connection.
        userStatusDatabaseRef.set(isOnlineForDatabase);
    });
});

Upvotes: 1

Related Questions