refetch only when window is active

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-24 22:45:48 +02:00
parent 1405acc4f6
commit 0e361c1c52
2 changed files with 24 additions and 15 deletions

View File

@@ -7,6 +7,7 @@ import {
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { useDebounceVal } from '@/hooks/useDebounceVal';
import useWS from '@/hooks/useWS';
import { cn } from '@/utils/cn';
import { useQueryClient } from '@tanstack/react-query';
@@ -23,40 +24,46 @@ const AnimatedNumbers = dynamic(() => import('react-animated-numbers'), {
loading: () => <div>0</div>,
});
const FIFTEEN_SECONDS = 1000 * 15;
const FIFTEEN_SECONDS = 1000 * 30;
export default function LiveCounter({ data = 0, projectId }: LiveCounterProps) {
const client = useQueryClient();
const [counter, setCounter] = useState(data);
const counter = useDebounceVal(data, 1000, {
maxWait: 5000,
});
const lastRefresh = useRef(Date.now());
useWS<number>(`/live/visitors/${projectId}`, (value) => {
if (!isNaN(value)) {
setCounter(value);
counter.set(value);
if (Date.now() - lastRefresh.current > FIFTEEN_SECONDS) {
lastRefresh.current = Date.now();
toast('Refreshed data');
client.refetchQueries({
type: 'active',
});
if (!document.hidden) {
toast('Refreshed data');
client.refetchQueries({
type: 'active',
});
}
}
}
});
return (
<TooltipComplete content={`${counter} unique visitors last 5 minutes`}>
<TooltipComplete
content={`${counter.debounced} unique visitors last 5 minutes`}
>
<div className="flex h-8 items-center gap-2 rounded border border-border px-3 font-medium leading-none">
<div className="relative">
<div
className={cn(
'h-3 w-3 animate-ping rounded-full bg-emerald-500 opacity-100 transition-all',
counter === 0 && 'bg-destructive opacity-0'
counter.debounced === 0 && 'bg-destructive opacity-0'
)}
/>
<div
className={cn(
'absolute left-0 top-0 h-3 w-3 rounded-full bg-emerald-500 transition-all',
counter === 0 && 'bg-destructive'
counter.debounced === 0 && 'bg-destructive'
)}
/>
</div>
@@ -69,7 +76,7 @@ export default function LiveCounter({ data = 0, projectId }: LiveCounterProps) {
damping: 10,
stiffness: 200,
})}
animateToNumber={counter}
animateToNumber={counter.debounced}
locale="en"
/>
</div>