I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause,

import React, { useEffect, useState } from 'react';
import VideoCardComponent from './VideoCard';
import Grid from '@mui/material/Grid';
import { connect } from 'react-redux';
import { getVideos } from '../redux/actions/videosActions&Consts';
import { Typography } from '@mui/material';

const Content = ({ getVideos, videos, loaded }) => {
    const [ currentGroup, setCurrentGroup ] = useState('');
    const [ printCurrentGroup, setPrintCurrentGroup ] = useState(true);
    const [ firstTime, setFirstTime ] = useState(true);
    useEffect(() => {
        if (!loaded) {
            getVideos();
        }
    }, []);

    const getVideoCard = (videoObj) => {
        console.log(videoObj);
        if (firstTime) {
            setFirstTime(false);
            setCurrentGroup(videoObj.category_name);
        } else {
            if (videoObj.category_name !== currentGroup) {
                setPrintCurrentGroup(true);
                setCurrentGroup(videoObj.category_name);
            } else {
                if (printCurrentGroup) setPrintCurrentGroup(false);
            }
        }
        return (
            <Grid item xs={4}>
                {printCurrentGroup ? <Typography variant="h4">{videoObj.category_name}</Typography> : null}
                <VideoCardComponent {...videoObj} />
            </Grid>
        );
    };
    console.log('videos: ', videos);
    return (
        <Grid container spacing={1}>
            {videos.map((videoObj) => {
                return getVideoCard(videoObj);
            })}
        </Grid>
    );
};

function mapStateToProps(state) {
    return {
        videos: state.videosReducer.videos,
        loaded: state.videosReducer.loaded
    };
}

function mapDispatchToProps(dispatch) {
    return {
        getVideos: () => {
            return dispatch(getVideos());
        }
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Content);

The Videos variable is essentially an array containing 7 objects. The issue surfaces when manipulating the state variables.

        if (firstTime) {
            setFirstTime(false);
            setCurrentGroup(videoObj.category_name);
        } else {
            if (videoObj.category_name !== currentGroup) {
                setPrintCurrentGroup(true);
                setCurrentGroup(videoObj.category_name);
            } else {
                if (printCurrentGroup) setPrintCurrentGroup(false);
            }
        }

Below is the segment of code leading to rendering this component:

        <Provider store={configStore}>
            <Grid container direction="column">
                <Grid item>
                    <Header />
                </Grid>
                <Grid item container>
                    <Grid item xs={2} />
                    <Grid item container>
                        <Content />
                    </Grid>
                </Grid>
                <Grid item xs={2} />
            </Grid>
        </Provider>

I'm seeking guidance on managing these state variables without triggering a re-render

Regards,

Answer №1

I managed to figure it out.

The issue lies in attempting to change state variables without implementing conditionals, as this results in infinite loops.

To solve the problem, I referred to a helpful post at

Rafael

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

Tips for utilizing JavaScript functions within Vue directives?

Let's say I have a JS function that looks like this: function myFunc() { return true; } Now, I want to display an element if the output of the function is true: <p v-if="myFun()">I am Test</p> I understand that I can place the myFun ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

React-select fails to trigger form submission when the Enter key is pressed

Currently, I am utilizing Formik and React-Select in my project, and I'm hoping to enable the form submission by pressing enter while focused on a select input. Interestingly, when I'm focused on any other input field and press Enter, the form s ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

The NodeJS server encountered an issue while trying to load the XMLHttpRequest from the localhost. The specified link type of

When accessing the same link to a jsx file (containing ReactJS code) online, everything works fine. However, when attempting to open it on NodeJS localhost, an error occurs: "XMLHttpRequest cannot load http://.../js/r1BodyBabel.js. No 'Access-Contro ...

Steps to Utilize Google Apps Script from a Website

I've been on a mission to find the solution to my problem. I have a basic web page with HTML/CSS/JS. What I want is for users to visit the page and immediately have it call up a Google script I created, which will pull information from a spreadsheet a ...

Should Redux Reducer deep compare values or should it be done in the Component's ShouldComponentUpdate function?

Within my React Redux application, I have implemented a setInterval() function that continuously calls an action creator this.props.getLatestNews(), which in turn queries a REST API endpoint. Upon receiving the API response (an array of objects), the actio ...

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

Tips for implementing real-time filtering using React Native Realm technology

As I transition to Realm for React Native, I am eager to take advantage of their built-in queries and filtering capabilities. Currently, I have checkbox filters with three options, and the selected options are stored in an array: var filters = ['comp ...

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

What is preventing me from mapping an array to Material UI Chip components?

I'm currently working with Next.js and I'm trying to map an array of elements to Material-UI chip components. However, when I compile the code, I encounter the following error: Error: Element type is invalid: expected a string (for built-in comp ...

Adjust Sidebar Height to Match Document Height (using React Pro Sidebar)

Having an issue with the height of a sidebar component in Next.js using React Pro Sidebar. It seems to be a JavaScript, HTML, and CSS related problem. I've tried several suggested solutions from Stack Overflow, but none of them seem to work. Surprisin ...

Guide on how to use Selenium to drag and drop a canvas web element specifically in the Chrome browser

Having trouble moving an image within the canvas web element (avatar editor) on Chrome using Selenium. Check out this canvas element: Watch a quick demo of what I'm trying to accomplish with Selenium Webdriver: Please review the code snippet below. ...

How can we stop the anchor jump caused by a third-party script?

I'm currently utilizing a third-party script (details provided below) to divide a form into multiple ajax'd pages. However, when I attempt to move on to the next page, it immediately jumps to an anchor at the top of the form. This behavior is unn ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

Encountering a problem while attempting to incorporate SQLite into a Node.js environment

I've encountered issues while attempting to import SQLite into node. Here is my import statement: import * as sqlite from './sqlite'; But unfortunately, I am receiving the following error message: node:internal/process/esm_loader:74 int ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

Maintain the Material UI TextField label at the top even when the text field is empty

I'm facing a simple issue that I can't seem to find a clear solution for. The labels in my setup are arranged as follows: https://i.stack.imgur.com/lPEid.png. At the bottom, the two fields have their labels on top due to default values, while t ...