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

Next.js Server Error: ReferenceError - 'window' is undefined in the application

I am currently in the process of integrating CleverTap into my Next.js application. I have followed the guidelines provided in the documentation Web SDK Quick Start Guide, however, I encountered the following issue: Server Error ReferenceError: window is ...

Utilize React Native to showcase JSON data in a visually appealing way by organizing it into titles and corresponding lists for both

I created a live code on Expo.io to showcase JSON data categories as titles and the subs as a list. This code utilizes .map() to retrieve data from an array. import React, { useState } from 'react'; import { Text, View, StyleSheet, Button, FlatLi ...

Extract the image URL from the href attribute using Xpath

My goal is to extract all images enclosed in href attributes from the given code snippet <div class="jcarousel product-imagethumb-alt" data-jcarousel="true"> <ul> <li> <a href="https://domain/imagefull.jpg" onclick="return false;" cla ...

The 'fs' module does not seem to have an immediate impact; a server restart may be necessary for the changes to take

This NodeJS project involves starting the server with npm start. The project reads files from a folder called "./mydir/" using 'fs.readdirSync'. It then pushes these files into an array and prints them on the console. var fs = require('fs ...

Building VSCode on Windows: A step-by-step guide

I am currently in the process of compiling https://github.com/Microsoft/vscode from the source code, but I am facing some challenges. After successfully running scripts\npm.bat install, I proceeded to run scripts\code.bat and a strange window app ...

Combining two-digit values

As a newcomer to JavaScript, I've been working on creating a basic calculator to practice my skills. However, I've run into an issue. When entering a double-digit number, the calculator is adding the digits together instead of treating them as se ...

Convert JSON data into an HTML table using JavaScript without displaying the final result

I need help troubleshooting my JavaScript code that is supposed to populate an HTML table with data from a JSON file. However, the table remains empty and I can't figure out why. Sample JSON Data [{"User_Name":"John Doe","score":"10","team":"1"}, { ...

After clicking on the checkbox, req.body.task becomes undefined

Whenever I click on the checkbox, the value of req.body.task returns as undefined. <input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})"> This function is triggered by a change event on the checkbox and it ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

Modify the URL and show the keyword utilized in a search module

Does anyone know how to update the URL in a search bar? I'm using Redux to display search results, but the URL remains the same. How can I make the URL show the keyword being searched, like this: http://localhost/seach?q=keyword ...

In React JS, the material-ui Accordion component's onchange function is failing to retrieve the current value

I am encountering an issue with the @material-ui Accordion where the onChange function is not capturing the current value. For example, when I click on the panel1 icon, it opens panel2 instead of taking the current value on icon click. I have provided the ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to comp ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

The code functions correctly on JSfiddle, however it is not executing properly on my website

When I tried to implement the code from this jsfiddle link: http://jsfiddle.net/mppcb/1/ on my website (), it didn't work as expected: Here is the HTML code snippet: <form id="myform" novalidate="novalidate"> <input type="text" name="fi ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

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 ...

Error message: Unable to access properties of undefined object (reading 'authorization')

This is a snippet of code that handles user authentication and authorization const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const userRepository = require("../repositories/userRepository"); const SALT ...