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

167
Visualizações
How can I call API when component mounts, then set an interval to call it x times after?
import fetchAppointments from 'src/redux/asyncThunkApiMethods';
import { useAppDispatch, useAppSelector } from 'src/redux/hooks';
import React, { useEffect, useState } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import { Table, TableHead, TableRow, TableCell, TableBody, Box, Typography } from '@material-ui/core';
import classes from '../../styles/AppointmentList.module.css';

const Appointments = (): JSX.Element => {
const appState = useAppSelector((state) => state.appointments);
const dispatch = useAppDispatch();
const location = useLocation();
const [isValid, setIsValid] = useState(false);

const bac = location.pathname.split('/')[5];

useEffect(() => {
if (!appState.loading) {
  if (!appState.errorMessage) {
    if (appState.appointmentList && appState.appointmentList.visits.length > 0) {
      setIsValid(true);
    }
  }
} else {
  dispatch(fetchAppointments({ bac }));
}

const interval = setInterval(async () => {
  await dispatch(fetchAppointments({ bac }));
}, 20000);

return () => {
  clearInterval(interval);
};

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [appState.appointmentList, appState.loading, bac, dispatch]);

I have a useEffect which currently is making two API calls each time. I need to make one call when the component mounts, then set an interval that will call the API every 20 seconds. I don't want double calls each time. I have moved code around but can't seem to get anywhere.

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

0

Just declare the interval variable before useEffect. Before mounting, assign it a setInterval, and when unmounting, clear interval

let interval;
useEffect(() => {
if (!appState.loading) {
  if (!appState.errorMessage) {
    if (appState.appointmentList && appState.appointmentList.visits.length > 0) {
      setIsValid(true);
    }
  }
} else {
  dispatch(fetchAppointments({ bac }));
}

interval = setInterval(async () => {
  await dispatch(fetchAppointments({ bac }));
}, 20000);

return () => {
  clearInterval(interval);
};

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [appState.appointmentList, appState.loading, bac]);
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