TanStackT
TanStack10mo ago
63 replies
verbal-lime

Global Persisting Cache

Hiya, really confused with how i would go about having global persisting cache with tanstack start and tanstack query?

1) I see the docs only mention persisting it stuff in localstorage.. but i would like to have a global cache like nextjs.
2) Even if i do localstorage.. i get errors that localstorage is not defined

import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
import { QueryClient } from "@tanstack/react-query";
import {
  persistQueryClient,
  removeOldestQuery,
} from "@tanstack/react-query-persist-client";
import { createRouter as createTanStackRouter } from "@tanstack/react-router";
import { routerWithQueryClient } from "@tanstack/react-router-with-query";
import { DefaultCatchBoundary } from "./components/DefaultCatchBoundary";
import { NotFound } from "./components/NotFound";
import { routeTree } from "./routeTree.gen";

// NOTE: Most of the integration code found here is experimental and will
// definitely end up in a more streamlined API in the future. This is just
// to show what's possible with the current APIs.

export function createRouter() {
  const queryClient = new QueryClient();
  const persister = createSyncStoragePersister({
    storage: window.localStorage,
    retry: removeOldestQuery,
  });
  persistQueryClient({
    queryClient,
    persister: persister,
  });
  return routerWithQueryClient(
    createTanStackRouter({
      routeTree,
      context: { queryClient },
      defaultPreload: "intent",
      defaultErrorComponent: DefaultCatchBoundary,
      defaultNotFoundComponent: () => <NotFound />,
    }),
    queryClient,
  );
}

declare module "@tanstack/react-router" {
  interface Register {
    router: ReturnType<typeof createRouter>;
  }
}
Was this page helpful?