headplane/app/utils/useLiveData.ts

36 lines
800 B
TypeScript
Raw Normal View History

2024-12-31 10:30:14 +05:30
import { useRevalidator } from 'react-router';
import { useEffect } from 'react';
import { useInterval } from 'usehooks-ts';
2024-03-25 18:47:15 -04:00
interface Props {
2024-12-31 10:30:14 +05:30
interval: number;
2024-03-25 18:47:15 -04:00
}
export function useLiveData({ interval }: Props) {
2024-12-31 10:30:14 +05:30
const revalidator = useRevalidator();
2024-03-26 09:28:52 -04:00
// Handle normal stale-while-revalidate behavior
2024-03-25 18:47:15 -04:00
useInterval(() => {
if (revalidator.state === 'idle') {
2024-12-31 10:30:14 +05:30
revalidator.revalidate();
2024-03-25 18:47:15 -04:00
}
2024-12-31 10:30:14 +05:30
}, interval);
2024-03-25 18:47:15 -04:00
2024-03-26 09:28:52 -04:00
useEffect(() => {
const handler = () => {
if (revalidator.state === 'idle') {
2024-12-31 10:30:14 +05:30
revalidator.revalidate();
2024-03-26 09:28:52 -04:00
}
2024-12-31 10:30:14 +05:30
};
2024-03-26 09:28:52 -04:00
2024-12-31 10:30:14 +05:30
window.addEventListener('online', handler);
document.addEventListener('focus', handler);
2024-03-26 09:28:52 -04:00
return () => {
2024-12-31 10:30:14 +05:30
window.removeEventListener('online', handler);
document.removeEventListener('focus', handler);
};
}, [revalidator]);
return revalidator;
2024-03-26 09:28:52 -04:00
}