Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to define the initial state - the code crashes with an error message stating

Too Many re-renders. React limits the number of renders to prevent an infinite loop.

    const [measures, setMeasures] = useState([]);
    const [duration, setDuration] = useState([]);
    const [word, setWord] = useState('Increasing')

    useEffect(() => {
        api.get('measures').then(res => {
            setMeasures(res.data.measures);
            // let a = res.data.measures
        });
    }, []);
    
    const total = measures.map((duration) => {
        return parseFloat(duration.duration);
    });

    setDuration(total) <<<<<HERE IS CRASHING 

    const action = () => {
        if (word === 'Increasing') {
            setWord('Decreasing');

            const increasing = () => {
                let organiseIncrease = total.sort(function (a, b) {
                    return (b - a)
                });
                setDuration(organiseIncrease);
            };
            increasing()
        } else {
            setWord('Increasing');

            const decreasing = () => {
                let organiseDecreasing = total.sort(function (a, b) {
                    return(a - b)
                });
                setDuration(organiseDecreasing)
            };
            decreasing()
        }  
    }

The "total" variable returns numbers like [15, 12, 50]. My goal is to automatically render this array when entering the page and then clicking the button to organize it in either increasing or decreasing order. I attempted to update the hook to:

const [duration, setDuration] = useState([total]);

But it returns: [undefined]. I considered wrapping everything in a function and using Async/Await to fill the hook, but I'm unsure if this approach will be successful. Any suggestions on how to address this issue?

Answer №1

The problem lies exactly where you specified, right here:

setDuration(total) <<<<<HERE IS CRASHING 

In this code block, you are updating the state within the main function without it being enclosed in a useEffect() or an event handler function. This causes the state to be updated on every render, triggering re-renders indefinitely.

It's similar to this scenario:

A -> B -> A  // Creating an infinite loop

Solution:

Move this code inside a useEffect() like so:

useEffect(() => {
  ...
  setDuration(total);
  ...
}, []);

Answer №2

When you make updates to the State, it triggers a re-render of the code. To update your code effectively, consider incorporating the following changes:

useEffect(() => {
        api.get('measures').then(res => {
            setMeasures(res.data.measures);
            // let a = res.data.measures
             const total = res.data.measures.map((duration) => {
                  return parseFloat(duration.duration);
              });

              setDuration(total); 

        });
    }, []);
 

Answer №3

The issue arises because the setDuration function is being called after the mapping of measures, which occurs in every render cycle of React. This code snippet is executed when a re-render happens.

Try making some adjustments to the code as shown below:

useEffect(() => {
    api.get('measures').then(res => {
        setMeasures(res.data.measures);
        // let a = res.data.measures
        setDuration(res.data.measures.map((duration) => parseFloat(duration.duration)));
    }, []);

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

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

Comparing Selenium and Watir for JavaScript Testing within a Rails environment

In our experience with Rails apps, we have found success using RSpec and Cucumber. While Webrat is effective for non-AJAX interactions, we are now gearing up to write tests for our Javascript. We have used Selenium support in Webrat before, but I am inter ...

Activating Button within Featherlight Modal

This is a follow up question from Featherlight hide div on Close After successfully resolving the issue with opening the lightbox, I have encountered another problem. I have added a submit button that should trigger an on('submit', function) whe ...

Webpack Is Having Trouble Parsing My JavaScript Code

I recently started using webpack and I'm struggling to get it to work properly. I haven't been able to find anyone else experiencing the same issue as me. Every time I attempt to run "npm run build" to execute webpack, I encounter this error: ER ...

Struggling with inserting a fresh form into every additional <div> section

During my quest to develop a To-Do list application, I encountered a new challenge. In my current implementation, every time a user clicks on New Category, a new div is supposed to appear with a custom name and a specific number of forms. However, an issu ...

Obtain a collection of the corresponding keys for a given value from dictionaries

I'm implementing a function that retrieves a list of keys associated with a specific value in the dictionary. Although I am able to print out the first key successfully, I'm facing difficulties in displaying subsequent keys. I understand that I ...

After the main page is loaded, the div will be dynamically populated with HTML content. How can we confirm that it has finished

I recently took over a project where a page loads and then code attached to that page populates a div with dynamically generated html – essentially filling an existing div with a string of html elements. Within this string are links to images, among oth ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

NG-model not visible to AngularJS Controller's filter

Finally, the code is working perfectly. It's a mystery to me. I created a custom filter to use with ng-repeat. The code is implemented within a Controller ... .controller('makeOrderController', function ($scope, $timeout, $ionicLoading) { ...

Iterate over a collection of HTML elements to assign a specific class to one element and a different class to the remaining elements

Forgive me if this is a silly question, but I have a function named selectFace(face); The idea is that when an item is clicked, it should add one class to that item and another class to all the other items. This is what I currently have: HTML <div c ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Having issues transferring values from one page to another. Any suggestions to make it work correctly?

I currently have two pages within my website, one is called details.page and the other is maps.page. In the details page, I have set up a search input as shown below : <form method="get" id="form-search" data-ajax="true" action="maps.page"> ...

When using res.redirect in Express, it not only redirects to a new URL but also allows you to access the HTML

I'm having an issue with redirecting a user to a login page when they click a button. Instead of being redirected, I am receiving the html source code and nothing is happening. My express redirect method is as follows: function customRedirect(req, ...

Incorporate the operating hours of a Business

If I specifically choose Sunday and Monday with working hours ranging from 08.00 to 20.00, the output should be 1&08:00&20:00,2&08:00&20:00. How can I achieve this using Vue.js? This is my current code: <script> submitBox = new Vue( ...

The powerful combination of Ajax and Django creates a dynamic Like button

Encountering difficulties while trying to implement a basic like button feature. Despite following various tutorials, clicking on the Like button does not yield any action. See below: models.py class Comentario (models.Model): titulo = models.CharFie ...

Attempting to populate HTML content retrieved from my MySQL database

Currently, I am attempting to retrieve HTML content stored in my MySQL database using nodejs. The products are being retrieved from the database successfully. export async function getAllProducts() { try { const response = await fetch('ht ...

What is the method to track the number of tspan elements within each span element?

How can I use jQuery to count the tspan elements inside multiple span elements within svg text? var count_tspan = jQuery('span text').children().length; // 4 console.log(count_tspan); <div class="content-inner"> <span id="item-0" cl ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Are you experiencing issues with the .submit() function when used in conjunction with other

Currently, I am working on a survey form that incorporates JQuery to dynamically display or hide fields based on user selections. //FORM CONDITIONALS: This script is responsible for hiding all the helpfulness radios and only displaying them when "Yes" fo ...

Uploading images dynamically using Ajax and PHP upon submission

Currently, I am working on a modal that submits information and an image through a form to a database using PHP and JavaScript. However, my expertise in JavaScript is limited, so I could use some assistance. So far, I have successfully inserted data from ...