Ardit Gjeloshaj
Ardit Gjeloshaj

Reputation: 21

Meteor, ReactJS, MongoDB: Do something when user leaves page

I am trying to build a match-making algorithm that connects two random users, but I can't find a way to delete the connection (which is generated in a MongoDB collection, so I need to remove the query) when user leaves the page.

Upvotes: 0

Views: 60

Answers (2)

xSkrappy
xSkrappy

Reputation: 747

How Does the user trigger the leaving of page , is it via a button click? after a time interval? MongoDB is realtime , and if the connection between the two users is based from the database , setting the database connection to null or deleting its instance + the usage of publish and subscribe will do the trick. Here is an example:

      const CheckIfConnection  = Meteor.subscribe('collectionsubscription',userId1,userId2)
          if(CheckIfConnection.ready()){
                 const connection = Collection.'ConnectionCollectionName'.findOne();

                //Pass it on the component
           }

on the Component side , you can have a 'ComponentWillReceiveProps' that will be triggered when a prop ( Coming from the container ) has changed and that is if the connection is Gone. That would do the trick at your matching algorithm via database approach :)

Upvotes: 0

Brett Merrifield
Brett Merrifield

Reputation: 2310

Maybe window.onbeforeunload will be helpful here. It executes Javascript when the user leaves the page.

Meteor:

Meteor.startup(function(){
    $(window).bind('beforeunload', function() {
        closingWindow();
    });
});

closingWindow = function(){
    ...
}

React:

componentDidMount() {
  window.addEventListener('beforeunload', this.handleLeavePage);
}

componentWillUnmount() {
  window.removeEventListener('beforeunload', this.handleLeavePage);
}

handleLeavePage() {
  ...
}

Upvotes: 1

Related Questions