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

68
Visualizações
useEffect runs in a loop

In my React app I use a useEffect function but it runs continuously, it produces too much request to the api. If someone has an idea to make useEffect execute more once the requested values are received

Here is my script :

import React from 'react';
import { useState, useEffect } from "react";

function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null)
useEffect(() => {
if (!data) (
fetch("http://localhost:4500/coingecko")
.then(response => {
  if (response.ok) {
    return response.json()
  }
  throw response;
})
.then(data => {
  setData(data)
})
  .catch(error => {
  console.error("Error fetching data: ", error)
  setError(error)
})
.finally(() => {
  setLoading(false)
}))
}, [])

//console.log(data)

const uniswap = data&&data[0].tickers?.find(donne => donne.trade_url === 
'https://app.uniswap.org/#/swap? 
inputCurrency=0x2260fac5e5542a773aa44fbcfedf7c193bc2c599&outputCurrency=ETH')
const uniprice = uniswap?.converted_last?.usd
const sushiswap = data&&data[2].tickers?.find(donne => donne.trade_url === 
'https://app.sushi.com/swap? 
inputCurrency=0x2260fac5e5542a773aa44fbcfedf7c193bc2c599&outputCurrency=ETH')
const sushiprice = sushiswap?.converted_last?.usd
const curvefinance = data&&data[3].tickers?.find(donne => donne.base === 'DAI')
const curveprice = curvefinance?.converted_last?.usd
const quickswap = data&&data[4].tickers?.find(donne => donne.trade_url === 
'https://quickswap.exchange/#/swapinputCurrency=0x0d500b1d8e8ef31e21c99d1db9a6444d3ad
f1270&outputCurrency=0xbbba073c31bf03b8acf7c28ef0738decf3695683')
const quickprice = quickswap?.converted_last?.usd
console.log(uniprice)
console.log(sushiprice)
console.log(curveprice)
console.log(quickprice)

return (
<>{uniprice}</>
)
}

export default App

Here is the console.log output:

enter image description here

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If you don't want to make a big modification, I see that you leave the Set as "Null" then instead of calling

useEffect(() => {
     if(data === null) (
       fetch("http://localhost:4500/coingecko")
       .then(response => {
            if (response.ok) {
                return response.json()
            }
       throw response;
       })
       .then(data => {
            setData(data)
       })
       .catch(error => {
             console.error("Error fetching data: ", error)
             setError(error)
       })
       .finally(() => {
             setLoading(false)
       }))
 }, []);

Just change to evaluate !data to data === null since it is your initial definition

about 4 years ago · Santiago Trujillo Relatório

0

You're using !data as your condition which test the "truthiness", which is not concrete enough. You need a strong condition or none at all.. With an empty dependency array, you will have one fetch at load to the api whether you specify data===null or not..

about 4 years ago · Santiago Trujillo Relatório

0

I copied your code to a sandobx and replaced the api with a public JSON api. I'm not able to reproduce the issue. However, I'd suggest not having !data as your condition to fetch, since you're only fetching the data onMount. Maybe something like this:

  useEffect(() => {
    const fetchData = () => {
      fetch("url")
        .then((response) => {
         ...
        })
        .then((data) => {
        ..
        })
        .catch((error) => {
         ..
        })
        .finally(() => {
          ..
        });
    };

    fetchData();
  }, []);
about 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