Click here to Skip to main content
15,882,209 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am building a display board. I want to call the API when the component first mounts. Then, I want to create an interval that calls that API every 20 seconds. Currently I dispatching two calls. I know why it's happening, but haven't been able to find the solution. (I am a beginner in web dev)

What I have tried:

TypeScript
<pre>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];

  const createInterval = () => {
    const interval = setInterval(() => {
      dispatch(fetchAppointments({ bac }));
    }, 1000);
  };

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

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

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

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

  const createData = (time: string, customer: string, vehicle: string, rewards: string, advisor: any) => {
    return { time, customer, vehicle, rewards, advisor };
  };

  return (
    <>
      <h1>{appState.appointmentList.greeting}</h1>

      {appState.loading ? <p>loading...</p> : null}
      {isValid ? (
        <Box width="100%">
          <Table aria-label="simple striped table" className="gds-table">
            <TableHead className="gds-table-header">
              <TableRow>
                <TableCell className="gds-table-cell">TIME</TableCell>
                <TableCell className="gds-table-cell">CUSTOMER</TableCell>
                <TableCell className="gds-table-cell">My GM Rewards</TableCell>
                <TableCell className="gds-table-cell">VEHICLE</TableCell>
                <TableCell className="gds-table-cell">SERVICE ADVISOR</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {appState.appointmentList.visits.map((visit) => (
                <TableRow className="gds-table-row-striped">
                  <TableCell className="gds-table-cell">{visit.appointmentTime}</TableCell>
                  <TableCell className="gds-table-cell">{`${visit.customer.firstName} ${visit.customer.lastName.charAt(
                    0,
                  )}`}</TableCell>
                  <TableCell className="gds-table-cell">
                    <img src={visit.customer.myRewardsTier} alt="Rewards" height="100" width="100" />
                  </TableCell>
                  <TableCell className="gds-table-cell">{`${visit.vehicle.year} ${visit.vehicle.make} ${visit.vehicle.model}`}</TableCell>
                  <TableCell className="gds-table-cell">
                    <img alt="Advisor" src={visit.advisor.mediaUrl} height="100" width="100" />
                    {visit.advisor.firstName}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>
      ) : (
        <p>{appState.appointmentList.noAppointmentsMessage}</p>
      )}
      <p>{appState.errorMessage}</p>
    </>
  );
};

export default Appointments;
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900