Is there a way to retrieve real-time information using momentjs in a Vue.js application without needing to refresh the

I have a unique table where I showcase details about a particular website. Among the displayed information is the timestamp indicating when the data was last updated.
At the top of the table, my aim is to include an icon that will only appear if the duration between now and the last data refresh exceeds 5 minutes. Furthermore, I desire for this time display to automatically update without necessitating a page refresh from the user.

In order to implement this functionality, I incorporated a specific component within my Vue.js code.

computed () {
getMinutesPassedSinceLastRefresh () {
     if (moment(this.currentTime).diff(this.lastRefreshTime, 'minutes') >= 5) {
        return moment(this.currentTime).diff(this.lastRefreshTime, 'minutes')
      }
  }
}

This function calculates the number of minutes elapsed since the data was last refreshed up to the present time. Nevertheless, the data does not dynamically update by itself; instead, it requires either a manual page refresh or switching tabs for it to reflect the latest information.

Do you have any creative solutions on how this issue can be resolved?

Answer №1

Using setInterval to update the currentTime value and a computed property to show the time difference in your HTML template is key.

Check out this implementation:

new Vue({
  el: "#app",
  data: {
    currentTime: moment(),
    lastUpdatedAt: moment(),
    intervalRef: null,
  },

  computed: {
    difference() {
      return moment.duration(this.lastUpdatedAt.diff(this.currentTime)).humanize(true)
    }
  },

  mounted() {
    this.intervalRef = setInterval(() => {
      this.currentTime = moment()
    }, 5000)
  },

  unmounted() {
    this.intervalRef = null
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96fbf9fbf3f8e2d6a4b8a4afb8a2">[email protected]</a>/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Time elapsed since last update: {{difference}}</h2>
</div>

This code snippet updates the time every 5 seconds.

For more information on Moment difference, visit: https://momentjs.com/docs/#/durations/diffing/

See an example on JSFiddle: JSFiddle Example

Answer №2

It looks like the currentTime and/or lastRefreshTime variables may not be reactive - make sure they are properly defined in the data section with default values assigned. Here is an example of how it should be done:

data () {
  return {
    currentTime: null,
    lastRefreshTime: null
  }
}

The initial values can be anything, but it's crucial that they are defined.

In addition, computed properties should return a value instead of relying on undefined. While it is uncertain if this could be causing the problem, try structuring it like this:

const minutesSinceLastUpdate = moment... // calculate minutes
return minutesSinceLastUpdate > 5
  ? minutesSinceLastUpdate
  : null

Check out the documentation on reactivity for more information

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

Incorporate PrimeVue into Vue's custom elements

Can you guide me on integrating a PrimeVue component into a Vue3 custom element? I have created a Vue3 composition+setup custom element. I expect the button to be styled with PrimeVue and appear red due to the severity="danger" attribute. Howev ...

The altered variable refuses to show up

Currently, I am working on a project to create a Skate Dice program that will select random numbers and display the results simultaneously. Unfortunately, I have encountered an issue where the randomly generated number is not being shown; instead, it dis ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Vue.js - issue with filtering results not displaying correctly

I am currently working on an app that displays items from an external JSON file and I'm looking to implement a search input feature for filtering. Initially, the app was displaying items properly. However, once I added the filter function, it stopped ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

Flick user media cards left or right to uncover the following one

I am currently working on creating a widget that will display user media objects in a horizontal layout using ng-repeat. The goal is to allow users to swipe left or right to reveal the next media card, similar to the image shown below. In the example, you ...

When utilizing the map function with an array containing 168 objects in the state of a React application, a freeze of around 1

I encountered an issue when trying to update a property in a state array of objects after executing an axios.put request. Here is my code: States - useEffect //... const [volunteers, setVolunteers] = useState([]); //... useEffect(() => { async fu ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

How can I simulate keyboard events in Angular using a button click?

I've included separate buttons for Ctrl+z and Ctrl+y functionalities. When these buttons are clicked, I want them to perform the respective undo and redo actions programmatically. Below is the code snippet for this functionality. undoText(event:MouseE ...

Not enough resources error in ajax code for live update clock functionality

Recently, I developed a real-time clock that updates every second. Surprisingly, when I tested it on my local environment, everything worked perfectly without any errors. However, the situation drastically changed when I decided to upload it to my web host ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

A step-by-step guide on setting up a confirmation pop-up message using Gravity Forms

Has anyone attempted to implement a pop-up confirmation message in Gravity Forms? I am also looking to prevent the form from disappearing after submission. By the way, I have selected text as the confirmation type in my Gravity Form settings because I do ...

What is the best way to display various components on a single page?

Every user type within my app requires a unique dashboard. Currently, the admin vue appears as follows: <template> <main id="admin-main"> <header id="admin-dashboard-header" class="jumbotron"> <div> ...

What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data: First Set: let training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ]; Second Set: let skill = [ "P1, Shooting", "P2, Passing", ]; I need to combine both arrays bas ...

What steps can be taken to enable automatic playback for this slider?

After downloading the slider from this site, I've been attempting to enable autoplay on this slider but have not had any success. Can anyone provide guidance on how I can achieve this? I've tried modifying the code below without achieving the des ...

What is the best way to transform this code into a JavaScript string that can be evaluated at a later time?

I need a way to save this snippet of JavaScript code, make some modifications to it, and then evaluate it at a later time. Unfortunately, the online converter I tried using didn't produce the desired outcome. Original Code $Lightning.use("c: ...

Ajax fails to send requests to PHP after changing the URL directory

After struggling to find a solution to my query, I have come to the realization that it has not been asked before. Despite enabling rewrite rules on my apache2 server in the .htaccess file located in the root directory, I am facing an issue with my ajax sc ...