Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

89
Vistas
React firing unlimited requests

What I am trying to do?

I am trying to call an api that sends information and I want to render the information on to the react app. I have acheived what I wanted to however, there is a problem.

THE PROBLEM

React is firing unlimited request to the api as shown in the image below.

app.js

import React, { useState } from 'react';
import './css/main.css'

const App = () => {
  const [data, setData] = useState([]);
  fetch(`http://localhost/api/index.php`).then((res)=>{return res.json()}).then(
    (data)=>{
      setData(data)
    }
  )

  return (
    <div>
      {data.length > 0 && (
        <ul>
          {data.map(ad => (
            <li key={info.id}>
              <h3>{info.name}</h3>
              <p>{info.details}</p>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

React firing unlimited api requests

almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Why is it not working?

The reason why this happens is that you are fetching data and update state on the fly that causing component to rerender, then to fetch data again, set state, rerender (getting stuck in a loop).

How to solve?

You should use useEffect hook (read more here). Also, you can read more about data fetching on official documentation website here.

What will change in your code?

The whole fetch will be wrapped in a useEffect hook.

  useEffect(() => {
    fetch(`http://localhost/api/index.php`).then((res)=>{return res.json()}).then(
      (data)=>{
        setData(data)
      }
    )
  }, []);
almost 4 years ago · Santiago Trujillo Denunciar

0

you need to use useEffect(). The problem is when you set the data your component rendering from scratch and again fetching data and again setting and again again...

useEffect(() => {
    fetch(`http://localhost/api/index.php`)
        .then(res=>res.json())
        .then(data=>setData(data))
}, []);
almost 4 years ago · Santiago Trujillo Denunciar

0

This is because you are setting the state in the API response itself and state change triggers re-render.

This happens as follows: fetch API call -> Data response -> set state -> trigger re-render -> fetch API call and the cycle continuous and result in infinite API call.

Solution: Call the API inside useEffect, useEffect is a hook that triggers once when the page renders or when its dependency changes.

Update your app.js as follows:

    import React, { useState } from 'react';
    import './css/main.css'
    
    const App = () => {
      const [data, setData] = useState([]);
useEffect(()=> {
      fetch(`http://localhost/api/index.php`).then((res)=>{return res.json()}).then(
        (data)=>{
          setData(data)
        }
      ),[]
}
    
      return (
        <div>
          {data.length > 0 && (
            <ul>
              {data.map(ad => (
                <li key={info.id}>
                  <h3>{info.name}</h3>
                  <p>{info.details}</p>
                </li>
              ))}
            </ul>
          )}
        </div>
      );
    }
    
    export default App;
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda