TanStackT
TanStack3w ago
9 replies
sacred-rose

Server Function being called multiple times

Hello. I am trying to learn Tanstack start/React and I have a question on server functions behaviour. A server function I am calling in a page is being called multiple times, with a 1-2 seconds interval between each call. What could possible cause this? Some king of cache/stale time config I missed (didn't change anything from default)?

Here is my function:
import { createServerFn } from '@tanstack/react-start';
import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions';
import { count } from 'drizzle-orm';
import { database } from '~/database';
import { Characters, Users } from '~/database/entities';

export const fetchStatisticsFn = createServerFn({ method: 'GET' })
  .middleware([staticFunctionMiddleware])
  .handler(async () => {
    await new Promise((resolve) => setTimeout(resolve, 3000));

    const [usersRes, charsRes] = await Promise.all([
      database.select({ count: count() }).from(Users),
      database.select({ count: count() }).from(Characters),
    ]);

    const totalUsers = usersRes[0].count;
    const totalCharacters = charsRes[0].count;

    return {
      stats: {
        totalUsers,
        totalCharacters,
        totalMasterpieces: 50, // Fixed
      },
    };
  });
And my page:
import { Link } from '@tanstack/react-router';
import { Button } from '~/components/ui/button';
import { fetchStatisticsFn } from '~/features/public/data/statistics.fn';

export async function LandingPage() {
  const { stats } = await fetchStatisticsFn();

  return (
    <div>
      <h1>Landing Page</h1>
      <div>
        <p>Stats:</p>
        <ul>
          <li>Curators: {stats.totalUsers}</li>
          <li>Heralds: {stats.totalCharacters}</li>
          <li>Masterpieces: {stats.totalMasterpieces}</li>
        </ul>
      </div>
      <div className="flex gap-2">
        <Button asChild>
          <Link to="/auth/login">Login</Link>
        </Button>
        <Button asChild>
          <Link to="/auth/register">Register</Link>
        </Button>
      </div>
    </div>
  );
}
Was this page helpful?