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

165
Views
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 answers
Answer question

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