Skip to content

Instantly share code, notes, and snippets.

@tchak
Last active November 5, 2022 05:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tchak/bdcba6668610520fe8196747d5b27b4b to your computer and use it in GitHub Desktop.
Save tchak/bdcba6668610520fe8196747d5b27b4b to your computer and use it in GitHub Desktop.
Remix Refetch
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