Why does updating state lead to a re-rendering loop while setting state does not encounter the same issue?

Essentially, I have developed a REST Api that retrieves a list of components (sections) from a CMS along with their associated data. Each section in the UI is assigned a number to indicate its position, but certain sections are excluded from counting, such as a career block section. This numbering information is passed as a prop to each rendered section using the format :number=""

In my function, it iterates through the sections and increments the number if the component is included in the allowedNumerableSections array. If the component is not in the array, it will return false and increment the decrementAmount state variable.

For example, let's assume we have 5 sections:


Section1
Section2
Section3
Section4
Section5

If Section3 is not included in the allowedNumerableSections array, then when these sections are looped out with the :number prop for each section, it would look like:


<Section1 number="1" />
<Section2 number="2" />
<Section3 number="false" />
<Section4 number="3" />
<Section5 number="4" />

Therefore, Section3 is skipped in the numbering sequence. Consequently, the UI might display /01 for Section 1 and /03 for Section 4, indicating the correct numbering order.

The issue arises when I implement logic to increment the state variable. For some reason, it loops specifically 608 times and the final numbers end up showing something like /0-201 instead of /04, or /0-204 instead of /01.

Here is an excerpt of my code:


<template>
  <div class="sections">
    <component
      :is="getSection(section.__component)"
      v-for="(section, index) in sections"
      :key="index"
      :section="section"
      :number="getNumber(section, index)"
      class="section"
    />
  </div>
</template>

<script>
export default {
  name: "SectionStructure",

  ... // Components, props, data, methods, computed properties

};
</script>

However, when I manually set decrementAmount to a specific value like this.decrementAmount = 3, it correctly loops the desired number of times, although all indexes are reduced by 3. This outcome is not ideal.

Does anyone have insights into why this continuous looping behavior occurs?

Answer №1

It seems that with each re-render, the function getNumber recalculates, subsequently updating the value of number, creating a continuous loop. Have you considered assigning the value of number upon receiving the response, but before the initial render? (e.g. on mount, or preferably in the response handler)

mounted() {
  this.calculateNumber()
},
methods: {
  calculateNumber(apiResult) {
    let decrementAmount = 0
    apiResult.map(section => ({
      ...section,
      number: this.getNumber()
    }))
  }
}

Regarding the issue of getting 608, it is likely due to reaching the recursion limit. Unfortunately, I cannot provide specifics on how this limit is determined.

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

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

What is the best way to develop a JavaScript function that divides the total width by the number of table headers (`th`)?

I recently came across this amazing scrollable table on a website, but I'm facing an issue with resizing the headers equally. Due to my lack of knowledge in JavaScript, I'm uncertain about how to tackle this problem. My intuition tells me that a ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...

Get Angular events in the proper order

I am currently facing challenges with event handling in AngularJs. In my service, I send out events using the following line of code : $rootScope.$emit("FNH."+this.status, flowNodeHelper); When receiving the event in service "S1," I handle it as follows ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

What is the process for retrieving the updated document from the findOneAndUpdate function?

Utilizing MongoDB with Node.js, I installed the MongoDB module using npm install mongodb. I encountered an issue where updating an existing document did not return the updated document; instead, it returned the original one. Even after setting the returnN ...

What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions. ...

Localizing strings that are not saved in a database

Our web app will soon support multiple languages, a new feature we are excited to roll out! Currently, we utilize Handlebars for front-end templating and Node + Jade for back-end templating. As we prepare to implement language support, we're conside ...

Executing Javascript within an iframe

Is there a way to include a script in an iframe? I came up with the following solution: doc = $frame[0].contentDocument || $frame[0].contentWindow.document; $body = $("body", doc); $head = $("head", doc); $js = $("<script type='text/javascript&a ...

Vue and Summernote issue: Model content doesn't display in form when loaded from database

I am having an issue with my form that uses the Summernote wysiwyg editor multiple times. When I fill out the form, everything works correctly - the model is updated, content is displayed, and the data is saved to the database. However, when I try to edit ...

Adjust image loading according to screen dimensions

I am working on HTML code that currently displays an image. The code looks like this: <div> <img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" /> </div> My goal is to show a different image based on the screen si ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

Angular Controller encounters issue with event handler functionality ceasing

One of my Angular controllers has the following line. The event handler works when the initial page loads, but it stops working when navigating to a different item with the same controller and template. document.getElementById('item-details-v ...