Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

377
Visualizações
Getting infinite loop and not able to fetch data in React

This the code that is responsible for getting Data and updating the list:

import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
    log: []
}

let page = 1;

const cartSlice = createSlice({
    name: 'cart',
    initialState: initialState,
    reducers: {
        fetching: (state, payload) => {
            state.log = axios.get(`http://localhost:5000/fetch/?${page = payload.payload}`)
            // console.log(state)
        }
    }
})

export const {fetching} = cartSlice.actions;
export default cartSlice.reducer;

And this is the Home Page:

import React, {useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {fetching} from "../features/cardSlice";
import Cards from "./Cards";

export default function HomePage(){



    const dispatch = useDispatch();
    const {itemsList} = useSelector((store) => store.card)
    console.log(itemsList)
    const {pageNumber} = useSelector((store) => store.page);

    useEffect(()=>{
        dispatch(fetching(1));   **// This is where i call dispatch to update the state and get the data**
    })

    function cardMapper(items) {
        return(
            <Cards
                name = {items.name}
                key = {items.id}
                cuisine={items.cuisine}
                address={items.address}
            />
        )
    }

    return(
        <div>
            {/*{itemsList.map(cardMapper)}*/}
        </div>
    )
}

When i run this on localhost i am not able to get data, the console.log(itemList) is showing undefined and also the dispatch(fetching(1)) is called infinite times.

Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I am not able to understand why i'm getting an infinite loop and also why am i not getting the data.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I modified your code. To prevent infinite loop in using useEffect you should put [] as dependency And for the useSelector,the variable should not enclosed by {}. see the modified code below. As I see, it should be cart not card

Try this code instead

export default function HomePage(){

        const dispatch = useDispatch();
        const itemsList = useSelector((store) => store.cart)
        console.log(itemsList)
        const {pageNumber} = useSelector((store) => store.page);
    
        useEffect(()=>{
            dispatch(fetching(1));   **// This is where i call dispatch to update the state and get the data**
        },[])
    
        function cardMapper(items) {
            return(
                <Cards
                    name = {items.name}
                    key = {items.id}
                    cuisine={items.cuisine}
                    address={items.address}
                />
            )
        }
    
        return(
            <div>
                {/*{itemsList.map(cardMapper)}*/}
            </div>
        )
    }

also in reducer add a return

 fetching: async (state, payload) => {
          const newState = await axios.get(`http://localhost:5000/fetch/?${page = payload.payload}`)
          return newState; 
 }
about 4 years ago · Juan Pablo Isaza Relatório

0

You need added dependencies as an empty array. To remove the yellow squiggly line you need to add dispatch inside that dependencies array. however, react to ensure that dispatch dependencies never change and that you are not responsible for re-render your component.

useEffect(()=>{
 dispatch(fetching(1))
},[dispatch])
about 4 years ago · Juan Pablo Isaza Relatório

0

// this should end the infinite loop
useEffect(()=>{ dispatch(fetching(1)); // This is where i call dispatch to update the state and get the data }, [ ])

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda