Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase onDisconnect how to trigger other function

I am reading firebase doc on onDisconnect but it didn't quite mention the operation i am looking for. https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

Goal: when a connection is disconnected, I want to run a function that updates other data that is not related to this connection data.

My code is below:

let PlayerRef = database.ref("/players");
let MessageRef = database.ref("/messages");
let con=playersRef.child(0).push('test');   
con.onDisconnect().remove(); // yes i want to remove that current connection
// BUT I also want to update the MessageRef that is 
//using the data in the "con", how can I acheive this???

How would I achieve this?

like image 978
WABBIT0111 Avatar asked Feb 04 '23 21:02

WABBIT0111


2 Answers

You can attach an onDisconnect() handler to any location in your database and remove or write data to that location.

But realize that onDisconnect() works by sending the write operation to the Firebase servers up front. So you can write any value, as long as that value can be calculated on the client when you attach the onDisconnect listener.

like image 87
Frank van Puffelen Avatar answered Feb 07 '23 13:02

Frank van Puffelen


With onDisconnect() you can trigger function inside remove():

    this.ref.onDisconnect().remove((err)=> {
        if (err) {
            console.error('could not establish onDisconnect event', err);
        }
    });

You most to add 'if(err)' inside because for some reason it's execute right when you active the connection, and actually worst - it's remove all the data in that link on firebase database.

better way to add trigger when firebase is disconnect is this:

    const Ref = new Firebase('...firebaseio.com');
    Ref.child('users/water').on('value', (data) {
        if (data.val() == true) {
            /* trigger when disconnected */
        } else {
           /* trigger when connected */
        }
    });
like image 24
Israel Avatar answered Feb 07 '23 12:02

Israel