TanStackT
TanStack9mo ago
5 replies
verbal-lime

Caching a data loader's output with staleTime not working

I'm new to Tanstack Router/Start and am looking to implement standard ISR/stale while revalidate behaviour:

1) Data gets a bundled at build time
2) Cached data is served without the fetch functions being invoked for 30 minutes (
staleTime
)
3) When the
staleTime
is hit, serve cache data one more time, rebuild cache under the hood for the next request

In this implementation, I'm seeing
getRecentTrends
called on every page request though, rather than only once every 30 minutes. Am I doing this right?

import { createFileRoute } from '@tanstack/react-router';
import { createServerFn } from '@tanstack/react-start';

import { getCategoryDistributionByHour, getRecentTrends } from '@/lib/trends';

export const fetchTrends = createServerFn({ method: 'GET' }).handler(async () => {
    return await getRecentTrends();
});

export const fetchCategoryDistributionByHour = createServerFn({ method: 'GET' }).handler(async () => {
    return await getCategoryDistributionByHour();
});

export const Route = createFileRoute('/')({
  component: Home,
  loader: async () => {
    const trends = await fetchTrends();
    const trendsByHourlyCategories = await fetchCategoryDistributionByHour();

    return { trends, trendsByHourlyCategories };
  },
  staleTime: 30 * 60 * 1000,
});

function Home() {
  const { trends, trendsByHourlyCategories } = Route.useLoaderData();

  return (
    <div>...</div>
  );
}
Was this page helpful?