Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
¿Cómo puedo llamar a la API cuando se monta el componente y luego establecer un intervalo para llamarlo x veces después?
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]);

Tengo un useEffect que actualmente realiza dos llamadas API cada vez. Necesito hacer una llamada cuando se monta el componente, luego establecer un intervalo que llamará a la API cada 20 segundos. No quiero llamadas dobles cada vez. He movido el código pero parece que no puedo llegar a ningún lado.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Simplemente declare la variable de interval antes useEffect . Antes de montar, asígnele un setInterval , y al desmontarlo, borre el intervalo

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!