Force Gatsby to prefetch linked page

499 views Asked by At

In my app, I'm storing state in a global object (similar to, but not Redux). When users navigate around the site, I want this state to persist. Gatsby intelligently tries to prefetch page content for links it finds on the page, but sometimes when navigating to a particular route, the page is fetched from the server, the window reloads, and I lose my state.

A little more context: I'm already using the Gatsby Link component for every link in the app, and if needing to change routes programmatically, I'm using the Gatsby navigate function. I've tried storing state in location.state, but this is also wiped if the page is not prefetched.

Is there any way to force Gatsby to prefetch routes so I don't lose my app state?

UPDATE:

Adding code snippet from my gatsby-ssr.js in case that might be related:

// gatsby-ssr.js

import React from "react";
import wrapWithState from "@state/wrapWithState"; <-- this is a React context provider

import { SearchConfig } from "@modules/search/index";
import { DefaultLayout, HeaderWrap, Lang } from "@layout";

export const wrapRootElement = wrapWithState;

export const wrapPageElement = ({ element, props }) => {
  const { location } = props;

  return (
    <>
      <Lang currentPath={location.href} />
      <SearchConfig />
      <HeaderWrap currentPath={location.href} />
      <DefaultLayout {...props}>{element}</DefaultLayout>
    </>
  );
};
1

There are 1 answers

1
Z. Zlatev On

It's simple really. If a link is not generated using Link component it will behave just like a regular anchor and the browser will perform a page load (resetting your state). First identify which links act like regular links and see why Link component is not used there.