Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus.

Upon receiving the event, I trigger a method that fetches data using a Swagger client.

The goal is to update an array of activities after each click on the child component.

Within the activities array, there are items with a date property which is converted to a formatted string using Moment.js: {{myFromNow(item.date)}}

The issue arises when I fetch a fresh list of activities (and set it to vm.activities), where the topmost item's date briefly refreshes before being replaced by the new item. This flickering of the new date is noticeable visually.

methods:{
    getActivity(){
    let vm = this

      this.$swagger.Activity.Activity_activityAll(
        {
          filter: JSON.stringify({
            order: 'Date DESC',
            include: [{
              relation: 'person',
              scope: {
                order: 'DateCreated ASC'
              }
            }
            ]
          })
        }
      )
        .then(function (resp) {


          vm.$set(vm, 'activity', resp.body['activity'])


        })
}
}

The listener for the event is set up in the mounted hook:

  mounted () {
    let vm = this
    this.$eventBus.$on('childAction', () => {

      vm.getActivity()

    })
  },

When debugging, it is evident that the fromNow function is updated after the

vm.$set(vm, 'activity', resp.body['activity'])
operation, and the list is only fully updated at the end of the method execution: https://i.stack.imgur.com/j9oOk.png

Do you have any insights into what might be causing this behavior?

Answer №1

After analyzing the issue, it was discovered that another parallel call was causing the re-rendering of all reactive data before the initial ajax call had completed.

The solution involved adjusting the data in this.activity within a computed property by including the fromNow date to activities and then iterating over that modified property.

Here's how it can be done:

computed: {
    compActivities () {
      this.activities.forEach((item, index, arr) => {
        arr[index].ActivityDateInterval = moment(item.ActivityDate).fromNow(true)
      })
      return this.activities
    }
}

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

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Function cascading

I'm currently facing a slight confusion with the got module, available at https://www.npmjs.com/package/got. The sequence and structure of functions within this module has got me puzzled. It's clear that you can chain listeners and functions toge ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

Implement AngularJS to ensure that scripts are only loaded after the page has finished rendering

I am having trouble implementing the TripAdvisor widget on my website. It functions correctly when the page is refreshed, but it does not appear when navigating through links. Additionally, an error message is displayed stating that the document could not ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

What could be causing the issue with my custom AlloyEditor UI extension?

After following the instructions in this guide to integrate alloyeditor as a WYSIWYG editor into Contentful, I successfully added the extension to my contentful staging space. However, despite copying the html page from the github repository and includin ...

Discover the method to activate the back button feature on ajax pages

I am currently working on a website that is navigated in the following way: $(document).ready(function () { if (!$('#ajax').length) { // Checking if index.html has been loaded. If not, navigate to index.html and load the hash part with ajax. ...

Retrieving information in JSON format

My goal is to retrieve data from the info.php file in order to utilize it in my project. This is what the content of info.php looks like: <?php $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', ''); $sth = $dbh ...

Issue encountered in AngularJS: struggling to store the localStorage item in the scope variable

I've been trying to save the values from window.localStorage.getItem('job_id.done_tasks') into a $scope variable, but I'm encountering difficulties. Can you please review my code? $scope.done_tasks = {}; $scope.done_tasks = window.loca ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Encountering a problem with AngularJS when attempting to access an array and display an alert message

While working with Angular, I encountered an issue in trying to access content stored within an array. Upon reviewing the code, console.log(JSON.stringify($scope.lineItems)) was returning [[]]. However, when inspecting or setting a breakpoint on this line ...

The integration of single page applications and <form> elements is a powerful combination in web development

Is there still value in using a <form> element over a <div> element when developing single page applications? I understand the purpose of the <form> element for traditional form submissions with a full page reload, but in the context of ...

There was an error while trying to read the properties of undefined (specifically the state). Make sure to include this.state.a

I am struggling with an error that I have never encountered before. Despite having experience working with functional components, I am new to class components. I used create react app to install the application, but it seems like I might be missing a req ...