Last active
January 27, 2022 17:52
-
-
Save hnordt/21b0541295c3919ed267400edac1f98e to your computer and use it in GitHub Desktop.
This file contains 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 React from "react" | |
import { useLocation, useLoaderData, useFetcher } from "remix" | |
export default function useLoaderDataWithWindowFocusRefetching<LoaderData>() { | |
const loaderData = useLoaderData<LoaderData>() | |
const fetcher = useFetcher<LoaderData>() | |
const location = useLocation() | |
const pathnameRef = React.useRef(location.pathname) | |
React.useEffect(() => { | |
pathnameRef.current = location.pathname | |
}) | |
React.useEffect(() => { | |
function refetch() { | |
fetcher.load(pathnameRef.current) | |
} | |
window.addEventListener("focus", refetch) | |
return () => window.removeEventListener("focus", refetch) | |
}, [fetcher]) | |
return fetcher.data ?? loaderData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment