headplane/app/utils/useLiveData.ts

35 lines
776 B
TypeScript
Raw Normal View History

2024-03-25 18:47:15 -04:00
import { useRevalidator } from '@remix-run/react'
2024-03-26 09:28:52 -04:00
import { useEffect } from 'react'
2024-03-25 18:47:15 -04:00
import { useInterval } from 'usehooks-ts'
type Properties = {
interval: number;
}
export function useLiveData({ interval }: Properties) {
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') {
revalidator.revalidate()
}
}, interval)
2024-03-26 09:28:52 -04:00
useEffect(() => {
const handler = () => {
if (revalidator.state === 'idle') {
revalidator.revalidate()
}
}
window.addEventListener('online', handler)
document.addEventListener('focus', handler)
return () => {
window.removeEventListener('online', handler)
document.removeEventListener('focus', handler)
}
}, [revalidator])
}