Last active
November 5, 2022 05:10
-
-
Save tchak/bdcba6668610520fe8196747d5b27b4b to your computer and use it in GitHub Desktop.
Remix Refetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useEffect, useState, useRef } from 'react'; | |
import { useLocation } from 'react-router-dom'; | |
import type { ActionFunction } from 'remix'; | |
import { redirect, useSubmit } from 'remix'; | |
export const action: ActionFunction = async ({ request }) => { | |
const body = new URLSearchParams(await request.text()); | |
return redirect(String(body.get('path'))); | |
}; | |
export default function Refetch() { | |
return null; | |
} | |
export function useRefetch(path?: string) { | |
const location = useLocation(); | |
const submit = useSubmit(); | |
return () => | |
submit( | |
{ path: path ?? location.pathname }, | |
{ method: 'post', action: '/_refetch', replace: true } | |
); | |
} | |
export function useRefetchOnWindowFocus(path?: string) { | |
const shouldRefetch = useRef(false); | |
const isVisible = usePageVisible(); | |
const refetch = useRefetch(path); | |
useEffect(() => { | |
if (isVisible && shouldRefetch.current) { | |
refetch(); | |
} | |
shouldRefetch.current = true; | |
}, [isVisible]); | |
} | |
function usePageVisible() { | |
const [isVisible, setVisible] = useState(isDocumentVisible()); | |
const onFocus = useCallback(() => { | |
setVisible(isDocumentVisible()); | |
}, []); | |
useEffect(() => setupEventListeners(onFocus), [onFocus]); | |
return isVisible; | |
} | |
function isDocumentVisible(): boolean { | |
if (typeof document === 'undefined') { | |
return true; | |
} | |
return [undefined, 'visible', 'prerender'].includes(document.visibilityState); | |
} | |
function setupEventListeners(onFocus: () => void) { | |
if (window && window?.addEventListener) { | |
addEventListener('visibilitychange', onFocus, false); | |
addEventListener('focus', onFocus, false); | |
return () => { | |
removeEventListener('visibilitychange', onFocus); | |
removeEventListener('focus', onFocus); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment