25 lines · 728 B
import { useRouter } from "@tanstack/react-router";
import { useEffect, useState } from "react";

const SECOND_MS = 1000;

/** Re-runs route loaders on an interval while `active`, and returns a ticking clock for elapsed-time displays. */
export function usePollWhile(active: boolean, intervalMs: number): number {
  const router = useRouter();
  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    if (!active) return;
    const clock = setInterval(() => setNow(Date.now()), SECOND_MS);
    const poll = setInterval(() => {
      router.invalidate();
    }, intervalMs);
    return () => {
      clearInterval(clock);
      clearInterval(poll);
    };
  }, [active, intervalMs, router]);

  return now;
}