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

238
Visualizações
Set delay for axios get request in useEffect

I am using react js , and when rendering the page a useEffect is implemented to request to express server to get data from database, this works, but if the server is down it will keep on requesting thousands of times until the app crashes. Is there a way to set a delay between every re-request? Or is there a neater solution for this?

Below is my code:

  useEffect(() => {
    async function fetchData() {
      setisLoaded(false);
      axios
        .get("localhost:3001/locations")
        .then((response) => {
          if (response.data) {
            setLocations(response.data[0]);
            setTown(response.data[1]);
            setTowns(response.data[1]);
            setDistrict(response.data[2]);
            setDistricts(response.data[2]);
            setGovernorate(response.data[3]);
            setSector(response.data[4]);
            setSubSector(response.data[5]);
            setSubSectors(response.data[5]);
            setlicenseType(response.data[6]);
            setmarkerGroup(true);
            setZoomLevel(8);
            setisLoaded(true);
          }
        })
        .catch((e) => {
          seterrorFetchedChecker((c) => !c);
        });
    }
    fetchData();
  }, [errorFetchedChecker]);

And the express code is :

app.get("/locations", async (req, res) => {
  try {
    const sqlFetch =
      "SELECT * FROM industries_db; SELECT * FROM towns ORDER BY value; SELECT * FROM districts ORDER BY value ; SELECT * FROM governorates ORDER BY value;  SELECT * FROM sectors ORDER BY value; SELECT * FROM sub_sectors ORDER BY value; SELECT * FROM licensetype ORDER BY value ";

    await db.query(sqlFetch, async (err, result) => {
      if (err) {
        console.log(err);
        res.sendStatus(500);
      } else if (result.length > 0) {
        return res.send(result);
      }
    });
  } catch (error) {
    res.sendStatus(500);
  }
});

I know my code is not as professional, I'm still new to web dev, please feel free to give any comments to make the flow better and giving me advices in coding techincs.

Thank You!

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

0

This is because every time you have an error in your request you update the state and the useEffect function get fired again and again.

You can implement a check based on the error with this logic:

if there is an error on the request, wait a predefined amount of time and fetch data, otherwise fetch data immediately:

  useEffect(() => {
    async function fetchData() {
      setisLoaded(false);
      axios
        .get("localhost:3001/locations")
        .then((response) => {
          if (response.data) {
            setLocations(response.data[0]);
            setTown(response.data[1]);
            setTowns(response.data[1]);
            setDistrict(response.data[2]);
            setDistricts(response.data[2]);
            setGovernorate(response.data[3]);
            setSector(response.data[4]);
            setSubSector(response.data[5]);
            setSubSectors(response.data[5]);
            setlicenseType(response.data[6]);
            setmarkerGroup(true);
            setZoomLevel(8);
            setisLoaded(true);
          }
        })
        .catch((e) => {
          seterrorFetchedChecker((c) => !c);
        });
    }
    
    if(errorFetchedChecker){
        setTimeout(()=>{
            fetchData();
        },[1000])// 1 second
    } else {
        fetchData();
    }    
  }, [errorFetchedChecker]);

Another solution is to use axios retry policy and avoid to update the state with the error if there was an error yet, but the first solution is good enough.

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