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.
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]);