The continuous loop is triggered when attempting to pass array data from the API

Hello, I have been searching for a solution to my current issue without much success. The problem revolves around retrieving dates from Firebase and populating them into UI elements in my Vue app. My end goal is to align each date with the corresponding month in Vue and display them accurately on the interface. However, I am encountering difficulties as the data does not display properly and triggers an infinite loop warning.

Below is the code snippet that I have been working on:

data() {
    return {
      dates: [], <---- these dates will be fetched from Firebase
      months: [ 
       {name: 'Jan', createdOn: [] }, 
       {name: 'Feb', createdOn: [] }, 
       {name: 'Mar', createdOn: [] }, 
       {name: 'Apr', createdOn: [] }, 
       {name: 'May', createdOn: [] }, 
       {name: 'Jun', createdOn: [] }, 
       {name: 'Jul', createdOn: [] }, 
       {name: 'Aug', createdOn: [] }, 
       {name: 'Sept', createdOn: [] }, 
       {name: 'Oct', createdOn: [] }, 
       {name: 'Nov', createdOn: [] }, 
       {name: 'Dec', createdOn: [] }, 
     ]
    };
},
methods: {
 logNewDate() {
  let mons = this.months
  let dates = this.dates
  dates.forEach(date => {
    if(!mons[0].createdOn.includes(dates)) {
     mons[0].createdOn.push(date.createdOn)
    }
  })
    console.log(mons[0].name, mons[0].createdOn)    
 },
}
<div v-for="month in months" :key="month.name">
    <b-button 
    class="btn-circle btn-md" 
    >
      {{ month.name }}
    </b-button>
</div>
    {{ logNewDate() }}

In my initial approach, I used an array of month strings which resulted in multiple duplicate displays. To resolve this, I included an object within the "months" property where I can match incoming dates to their designated months. Despite successfully storing the dates using the forEach loop in the "logNewDate" function, it leads to repeated additions of the same dates causing an endless loop. Implementing checks like "includes()" did not prevent this issue.

If you could assist in identifying the root cause of this looping behavior and provide guidance on rectifying it, I would greatly appreciate it. Additionally, I am aware of the hardcoded indexes in the forEach loop and aim to make them dynamic based on the month saved from Firebase data.

The error screenshots can be viewed here: https://i.sstatic.net/IcfWC.png https://i.sstatic.net/8afMi.jpg

Answer №1

Prabir raised an interesting point. To tackle the issue at hand, I implemented a solution that utilized nested for-in loops.

As I delved into the inner loop to access the incoming dates, I transformed the date strings into date objects, shortened them to abbreviated month names, and then compared them using === against the predefined month strings in my month object.

Below is the final version of my code:

for(let i in this.months) {
    for(let j in this.incomingDates) {
        var dates = new Date(this.incomingDates[j].createdOn);
        const shortMonth = dates.toLocaleString('default', { month: 'short' });
        if(shortMonth === this.months[i].name) {
            this.months[i].createdOn.push(shortMonth);
            console.log(this.months[i].name, this.months[i].createdOn);
        }
    }
}

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

JavaScript Time Counter: Keeping Track of Time Dynamically

Currently, I am attempting to create a dynamic time counter/timer using JavaScript. Why dynamic? Well, my goal is to have the ability to display days/hours/minutes/seconds depending on the size of the timestamp provided. If the timestamp is less than a d ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

Utilizing the current state within a React callback function closure: A guide to maximising efficiency

I'm currently working on a web page that features a dynamic list of form inputs. Users have the ability to add or remove input fields using designated buttons. To manage this functionality, I've created a parent object called <Ingredients /> ...

Guide on implementing a check all and delete function using the datatables (jquery datagrid plugin)

I am currently utilizing the Datatables jQuery plugin to manage my table rows. While it comes with a tabletools plugin that allows for a checkall function, I am wondering how I can add a custom delete button and retrieve the selected row. Fortunately, I a ...

Vue component fails to display upon clicking v-btn with a designated route

I'm experiencing difficulty with loading a component. My web app has a Navbar with a Drawer that links to each main page. Currently, I have a page called "Weapons.vue" which displays weapon categories in a video game (such as Sniper Rifles and Handgu ...

Tips on displaying an array of elements as a <Dialog> within a <List>

I am currently developing a <ElementList> component that is designed to accept an array of elements through props and create a <List>, with each <ListItem> representing an element in the array. I have also included a separate component ca ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Can Vue Storefront Nuxt be seamlessly integrated with Algolia Search Routing in SSR for optimal performance?

Successfully integrated Algolia search with the VSF/Next branch, mastered the basics. Next up: tackling routing. While Vanilla Nuxt works smoothly with the integration, the number of workarounds is gradually increasing. To Reproduce: clone && yarn && ya ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

When is the best time to assign properties to mobx domain objects?

When it comes to tackling a specific problem in my react/mobx application, I'm facing challenges finding an optimal solution. Imagine having multiple boxes that need to be positioned on the screen based on various factors such as interdependency betwe ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Exploring the Use of async: false in jQuery

Can you tell me if there is a distinction between these two settings: $.ajax({ type: "POST", traditional: true, url: '/adminTask/doAction', async: false, <<<<<<<<<<<<<< HERE data: p ...

Creating seamless scrolling in ReactJS without any pre-built components

Can anyone guide me on how to implement an infinite scroll in reactJs using a JSON dataset? I prefer building it from scratch without relying on any library. {data?.map((conto) => { return ( <Suspense key={conto._uid} fallback={<p>Loadin ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

A simple guide on logging into Discord with token using the Selenium library in Python

I created a Python code using the selenium module to log in to Discord using a token number. The token number needs to be added to localStorage, so I used JavaScript code to add it successfully. However, upon checking Application -> localStorage -> h ...

What steps can be taken to modify the style of a single button belonging to a broader group of elements?

Is there a way to hide the save button within a Vue Modal without affecting other buttons with the same class? .btn.btn-primary { display: none; } Simply targeting .btn-primary in the CSS affects all elements with that class, and adding .modal woul ...