gatsby: Expose an API for manually triggering prefetching for a pathname

Summary

Currently there is no way to programmatically trigger the prefetching done for a pathname when the <Link> component is mounted.

Basic example

const fireEvent = () => {
  const id = createNewPerson();
  navigate(`/person?id=${id}`);
}
<button onClick={fireEvent}>Create Person</button>

Motivation

Developers might want to leverage prefetching when programmatically triggering navigate.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 6
  • Comments: 26 (10 by maintainers)

Commits related to this issue

Most upvoted comments

export function usePreFetch() {
  const ref = useRef(null)
  useEffect(() => {
    // @ts-ignore
    ref?.current?.dispatchEvent(
      new MouseEvent('mouseover', {
        view: window,
        bubbles: true,
        cancelable: true
      })
    )
  }, [])

  return ref
}

export const PreFetch: FC<{ page: Page }> = ({ page }) => {
  const ref = usePreFetch()
  return <Link to={page} ref={ref} />
}

this solves the problem, an invisible link that trigers a synthetic hover event on page load which causes the pre fetch to work

This seems pretty reasonable to me.

The API would be something like:

import { prefetchPathname } from "gatsby"

prefetchPathname(`/about/`)

I am on gatsby 2.32.2 and can import prefetchPathname, however, when I use it It does not seem to do anything. I don’t see many discussion around this api nor documentation/caveats.

i tried via useEffect(() => { prefetchPathname("/url") }, []) as well as via a class:componentDidMount method.

If I have a Link present, and hover over it, I see app-data.json and page-data.json load.

I’m also logging the flow found in in the gatsby/cache-dir/loader.js:prefetch() function and it does go all the way and adds the path to the ‘prefetchCompleted’ Set.

I’m a bit confused.

I would try reinstalling. Lookz like some deps are missing

Done!

@KyleAMathews Is this something that is still being worked on? Can it be re-opened, since as far as I know it’s not resolved yet?

It’s when the link appears in the viewport. We leverage https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for this.