Home > Software engineering >  How to refresh the table data when one of the item has its valid till date and time has expired in R
How to refresh the table data when one of the item has its valid till date and time has expired in R

Time:04-03

I have a table data where there are section called Item, Time and ValidTill so for example one of the Item has a time of April 2nd 2022, 3:08:01 pm and is ValidTill time of April 2nd 2022, 3:09:26 pm so after this validtill expires i have make an api call in useEffect which i am already doing it once the component mounts but i also want it to run when validTill expires so how can it be achieved

const [quotesData, setQuotesData] = useState([]);
useEffect(() => {
  getRandomdata();
}, []);
async function getRandomdata() {
  const result = await RandomApi.get(`/quotes/${symbolId}`);
  setQuotesData(result.data.payload);
}
    <Table stickyHeader className={classes.stickyHeader}>
      <TableHead>
        <TableRow>
          <TableCell>Item</TableCell>
          <TableCell>Time</TableCell>
          <TableCell>Validtill</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {quotesData.map(({Item, time, valid_till }) => (
          <TableRow key={Item}>
            <TableCell>{Item}</TableCell>
            <TableCell>
              {moment(time).format("MMMM Do YYYY, h:mm:ss a")}
            </TableCell>
            <TableCell>
              {moment(valid_till).format("MMMM Do YYYY, h:mm:ss a")}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>

CodePudding user response:

As there could be many rows in your table and you would like to listen to each row's expiry event so that you can send an API request for each specific row right??.

To achieve it you can use setInterval javascript function to set interval for each second and in the body of setInterval callback you can check for each rows expiry like this.

    useEffect(() => {
      setInterval(() => {
    // loop on each row an compare time to current time for expiration check if expired send the api request
        

    quotesData.map(({ Item, time, valid_till }) => {
      if (valid_till > currentTime) {
        // expired
        //send api request
      }
    });
  }, 1000);
});

this could be a good solution if your dataset is not too large. For larger datasets we have to do some more tweaks on the code.

CodePudding user response:

I used another approach, instead of running an interval polling for each item, which would be greedy, I think you could just calculate the time left from the moment the component is mounted to the expiry time and just place a timeout with the difference between those two dates, I made an example here, see if it can help you: https://stackblitz.com/edit/react-t5jfab

I placed just one item in the array, but it works with any amount of items, since it just cycles through them and places timeouts.

  • Related