Check for Vue: see if the user is disconnected and display a div for a brief moment when they reconnect

Currently, I have implemented a function within a timed loop to monitor if a user goes offline:

created() {
   setInterval(() => {
        this.checkOnline();
   }, 30000);
}

Function:

checkOnline(){
   this.status = navigator.onLine ? true : false;
}

Is there a more efficient way to detect online status without relying on a timer?

Additionally...

I want to display a brief alert message when the user comes back online. The idea is to hide a div element when the user is online or offline. When transitioning from offline to online, briefly show the div for about one second and then hide it again. I've attempted using setTimeout and watchers but haven't achieved the desired result.

Edit:

One approach that partially addresses this issue is:

 data() {
     return {
         status: navigator.onLine ? true : false,
     }
 }

Followed by a watcher to handle the back-online notification:

watch: {
    status: function (val) {
        if(this.status === true){
            this.showAlert = true;
            setTimeout(()=>{ this.showAlert = false; }, 1000);
        }
    },
},

Are there alternative methods to achieve this functionality other than utilizing a watcher or a dedicated notify plugin?

Answer №1

Is it possible to detect this without relying on a timer? Absolutely. By leveraging the online offline event.

Are there alternative methods to using a watcher or notify plugin for this task? I believe the watcher is the most effective approach in this scenario.

Example: https://jsfiddle.net/jacobgoh101/xz6e3705/4/

new Vue({
    el: "#app",
    data: {
        onLine: navigator.onLine,
        showBackOnline: false
    },
    methods: {
        updateOnlineStatus(e) {
            const {
                type
            } = e;
            this.onLine = type === 'online';
        }
    },
    watch: {
        onLine(v) {
            if (v) {
                this.showBackOnline = true;
                setTimeout(() => {
                    this.showBackOnline = false;
                }, 1000);
            }
        }
    },
    mounted() {
        window.addEventListener('online', this.updateOnlineStatus);
        window.addEventListener('offline', this.updateOnlineStatus);
    },
    beforeDestroy() {
        window.removeEventListener('online', this.updateOnlineStatus);
        window.removeEventListener('offline', this.updateOnlineStatus);
    }
})

Answer №2

To update the online status, you can simply use arrow functions in event listeners to set a variable to true or false based on the event. There is no need to constantly check for the navigator.online value or use interval timers. By setting up event listeners for the online and offline events provided by the window object, you can easily handle changes in connectivity. In the code snippet below, I have initialized an 'isOnline' variable based on the initial navigator.online value. Using event listeners for online and offline events, the variable is updated accordingly. This variable is then used in the template to display a message to the user using the v-if directive.

data() {
  return {
    isOnline: navigator.online
  }
},
mounted() {
  window.addEventListener('online', () => { this.isOnline = true });
  window.addEventListener('offline', () => { this.isOnline = false });
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected appearance of DOM elements

I've come across an unusual bug in a web application I've been developing that is reproducible in Chrome and Safari, but not in Firefox. To witness the bug, go to www.lastcalc.com and type a single uppercase letter. The letter will be immediatel ...

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

show the attributes of an item contained within an array of objects

Hey there! I'm facing an issue with displaying the content of an object on my HTML page using React. So, here's what's happening: I can access the frontend properties in my object array, but when I try to loop through each element and displa ...

Sending an array encoded in JSON to jQuery

I'm attempting to send an array that I've created in PHP using json_encode(). The process involves running an AJAX request, as shown below: AJAX CALL: $.ajax({ type: "POST", url: "../includes/ajax.php?imagemeta=1", data: ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

What is the best way to assign my function to dynamically generated cards in vanilla JavaScript using event delegation?

I've been experimenting with a card flip feature on dynamically generated elements. The first function I created only applied to the template, so I tried delegating the event to an existing HTML element. However, it's not functioning as expected. ...

Error message: Unable to run npm script serve due to permission issues with vue-cli-service

Attempting to execute a basic vue project, but encountering difficulties running it on my openSUSE TW (20200615) system. I have NVM for managing my node installation. Here is my current environment: nvm --version # 0.35.3 node --version # v14.4.0 npm --v ...

The footer is now accompanied by the <v-navigation-drawer> on the side

I am looking for a way to dynamically adjust the height value of a style applied to an element based on certain conditions. Specifically, when scrolling to the bottom, I want the height to be 77.5%, when the footer is not visible at all, it should be 100%, ...

Is there a way to view the contents of the dev server once it has been bundled by webpack?

From my understanding, webpack in dev mode stores all imported files in a certain location and then serves the bundle.js file to the client. If the code inside bundle.js requests a CSS file, the css-loader should have already been configured to provide t ...

JavaScript unable to access elements during page loading

I am facing an issue with the following code: var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); v ...

Having trouble importing a modified package forked for use in a Next.JS project

I've implemented react-headroom in my current project and had to modify its code so that the <header> wouldn't change height on different pages. To achieve this, I forked the original repository from here, made the necessary changes on my v ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

Concealing elements with HTML, CSS, and JavaScript by setting the display

Issue arose when I set my id="Gabel" display to none, resulting in distorted formatting. Any suggestions for correcting this? Desired outcome is to show display id="Gabel" upon clicking the image on the main page. Here are relevant co ...

What steps should be taken to safely sanitize untrusted JSON data before parsing it with JSON.parse method

How can we properly sanitize a user-provided JSON string to prevent any vulnerabilities before executing JSON.parse(untrustedString)? My main concern revolves around prototype pollution, but I'm also interested in knowing about any other potential ri ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

Query the key value pair from a string object using regular expressions such as { key=value, .... }

I'm trying to extract key value pairs from a string using regex. Here's an example string: "{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}" How can I convert this string into an object with the foll ...

Modify URL parameters using history.pushState()

Utilizing history.pushState, I am adding several parameters to the current page URL after performing an AJAX request. Now, based on user interaction on the same page, I need to update the URL once again with either the same set of parameters or additional ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...