Vue infinite loop occurring in a method

I keep receiving this warning

[Vue warn]: You may have an infinite update loop in a component render function.
and I believe I have pinpointed the reason behind it.

My Scenario : I am passing an object with an index to a Vue method within a loop. Computed properties cannot accept arguments, so I am left with using a method.

The objective is to increment the date by one week once the loop reaches an odd number, except for 1 and 2.

Below is the code snippet I've been working on:

getDate(date, i){
      var currentDate = date.startingDate;

      var res = currentDate;
      if(i > 2){
        // change the date 
         if(i % 2 == 0){
            //use previous dates 
            res = date.startingDate;
         }else{
            // increase the date by one week from the last week 
            var currDate = new Date(currentDate);
            var d = currDate.setDate(currDate.getDate() + 7);
            var d = new Date(d);
            var newDate = d.toISOString();
            var dateArr = newDate.split("T");
            var res = dateArr[0];
            console.log('ok');

            date.startingDate = res; // this particular line is causing the infinite loop issue

         }
      }

      return res;

  }

Here, date.startingDate always holds a fixed date value.

Sample Input

date.startingDate='2018-05-11'

So when

i=1 or 2 (i always starts from 1)
the output will be date.startingDate='2018-05-11'

For i=3 or 4, the date should be incremented by one week resulting in an expected output of 2018-05-17

The issue lies in the line date.startingDate=res. I need to reset the date to the newly increased value in order to add another new date when i=5,6, or more.

Are there any alternative solutions or potential improvements to this code? Any suggestions would be greatly appreciated.

Thank you for taking the time to review this.

Edit

<div class="row _6-2-1__Tou align-items-center team" v-for="(m,j) in data.row" :key="j">


     <div class="col-auto _6-2-1__Tou-one pad-0" >
       <ul class="_6-2-1__Tou-text">

        <li>{{getDate(m.date,j+1)}}</li>

      </ul>
     </div>

Answer №1

After encountering a persistent problem, I decided to change my approach. Instead of updating the date while populating the dom, I opted for using vuex store and getters. By making adjustments within the getters and returning the modified values once all changes were made, I was able to effectively resolve the issue. Below is the updated code snippet:

The logic in this code has been slightly altered with the addition of dynamic conditions, but the underlying concept remains the same.

fixture(state){
  // updates can be applied here

  for(var i in state.fixture){

      var details = state.fixture[i].row
      for(var j in details){   
          //console.log(details[j].date.startingDate)

          if(state.counter == state.groupCount){  

              // increment the date 
              if(state.date){
                var currDate = new Date(state.date) 
              } else{
                var currDate = new Date(details[j].date.startingDate) 
              }

              var d = currDate.setDate(currDate.getDate() + 7);  
              var d = new Date(d)
              var newDate = d.toISOString()
              var dateArr = newDate.split("T")
              var res = dateArr[0]
              details[j].date.startingDate = res 

              state.date = details[j].date.startingDate   

              state.counter = 1

          } else{

            if(state.date){ 
              details[j].date.startingDate = state.date 
            }

            state.counter++ 
          }

      }
      state.counter = 0
      state.date = ''
  }

  return state.fixture
},

I hope this revised approach proves beneficial to others facing similar challenges.

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

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Unveiling the magic of Vue Composition API: Leveraging props in the <script setup> tag

I'm currently working on creating a component that takes a title text and a tag as properties to display the title in the corresponding h1, h2, etc. tag. This is my first time using the sweet <script setup> method, but I've encountered a pr ...

Angular custom filter applied only when a button is clicked

I have recently started exploring angular custom filters and I am curious to know if there is a way to trigger the filters in an ng-repeat only upon clicking a button. Check out this example on jsfiddle : http://jsfiddle.net/toddmotto/53Xuk/ <div ...

Guide on combining two JSON Array objects in Nodejs

Is there a way to merge two JSON Array objects together using Node.js? I am looking to combine obj1 + obj2 in order to create a new JSON object: obj1 = [ { t: 1, d: 'AAA', v: 'yes' }, { t: 2, d: 'BBB', v: 'yes& ...

How to extract query string parameters using node.js

I'm currently working on fetching query string parameters from a URL using the node.js restify module. This is an example of the URL I am dealing with: Here is the relevant code snippet: server.use(restify.bodyParser()); server.listen(7779, functi ...

Activate the button when a checkbox is ticked or when using the "select all" checkbox

I'm facing an issue with a script that should enable a button when at least one checkbox is selected and a checkbox for selecting all checkboxes is used. The problem arises when I select the "select all" checkbox as it activates the button, but if I ...

"employing" the extent and characteristics using square brackets for notation

Can we access object properties that can only be accessed with square bracket notation while inside a "with" statement? For instance: var o = { "bad-property": 1, "another:bad:property": 2, "goodProperty": 3 }; with(o) { console.log(goodProperty); / ...

Ways to retrieve information when text is modified and a dropdown is selected within an input field

I have an input field with a text box and a dropdown. My goal is to trigger data based on text changes in one method, while using another method for the dropdown. Check out the code below. const allList = [ { id: "1", value: "Fruits" ...

Here's a tip on how to trigger a function when the text in an input box changes using JavaScript

While using Vue, I am developing a form which includes an input box. Whenever the text in the input box changes, it should update the function setMessage. <input type="text" v-model="test" v-on:change"setMessage"> However, the issue is that the upd ...

Update the style of a div within an iframe in React

I'm currently developing a project in Next.js and I've added an iframe within a component. The issue I'm facing is that I need to customize the style of a specific div inside the iframe, but I'm having trouble targeting the div with the ...

Utilize a React Switch Toggle feature to mark items as completed or not on your to-do list

Currently, I am utilizing the Switch Material UI Component to filter tasks in my list between completed and not completed statuses. You can view the demonstration on codesandbox The issue I'm facing is that once I toggle a task as completed, I am un ...

Add a photo - Django REST framework

I have two models, User and EcoUser, with a one-to-one relationship (I have omitted some fields for simplicity in this example): class User(AbstractUser): picture_url = models.ImageField(upload_to='logos/', blank=True) class EcoUser(models. ...

Sending a Single Input Field value to a Controller in Laravel using JQuery

Looking to submit a single form value using jQuery to a database in Laravel. Below is the input field: <input type="text" id="comment"> <button id="cmntSubmit" type="button">Post</button> Check out the jQuery code I am using: $(docum ...

After modifying the code for a 3D map exported from qgis2threejs, the page now sits empty, waiting

I'm looking to make modifications to the code within a 3D map that was created using qgis2threejs, which is QGIS's plugin for creating 3D webmaps. Although I don't have much experience with the threejs library or JavaScript, I want to alter ...

Obtaining a value from a protractor promise within a function and returning it

Is there a way to extract text from a webpage and use it for asserting on another element in the specification? Here is a simple example that demonstrates how you cannot return a value from a function within a Protractor promise: describe('My Test&a ...

Generate a data URL from the retrieved image

TL;DR I've been attempting to retrieve an image, convert it to base64, and insert the data URL into the src attribute of an img tag, but unfortunately, it's not functioning as expected: async function ajax(id) { const element = document.getEl ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

Using Vue.js, pull information from a database to populate input fields using a datalist feature

I'm currently working on a project utilizing Laravel 8 and Vue 3, and I have a Student Component. Within this component, there is a datalist that allows me to search for existing students. When I select a student from the list, I want the correspondin ...

Employing ng-style for establishing background when the value does not align

Greetings all! I am using ng-repeat to create a list of items within a ul element. Within the json data, there is a specific value that I want to highlight if it does not match a predefined string. Here's what I have so far: ng-style="{'backgro ...