Skip to content

Instantly share code, notes, and snippets.

@hnordt
Last active January 27, 2022 17:52
Show Gist options
  • Save hnordt/21b0541295c3919ed267400edac1f98e to your computer and use it in GitHub Desktop.
Save hnordt/21b0541295c3919ed267400edac1f98e to your computer and use it in GitHub Desktop.
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