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

91
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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