Last active
May 10, 2026 09:33
-
-
Save frstycodes/d40fd28683bc2722843c0df4fc7c1c6b to your computer and use it in GitHub Desktop.
Ideal data fetching strategy for Tanstack router/start with Tanstack query. You can omit the waitIfSSR function if you're not using SSR but make sure to not await the ensureQueryData function in the loader or navigation will feel slow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| async function waitIfSSR(...promises: Promise<any>[]) { | |
| if (typeof window === "undefined") await Promise.all(promises) | |
| } | |
| export const Route = createFileRoute("/_authed/dashboard/$id/accounts/")({ | |
| component: RouteComponent, | |
| validateSearch, | |
| beforeLoad: ({ search, params }) => ({ search, params }), | |
| /* | |
| Pass a promise to waitIfSSR function so it waits for the data to load if it's SSR so the users get the full page | |
| without any loading state on first page visit and if it's client side navigation, ensureQueryData triggers the fetch and | |
| you can show loading state so we don't block the navigation until data is ready. This makes page feel snappy and good for SEO as well. | |
| */ | |
| loader: ({ context }) => | |
| waitIfSSR( | |
| context.queryClient.ensureInfiniteQueryData( | |
| fetchAccountsQueryOpts({ | |
| search: context.search.search, | |
| vaultId: context.params.id, | |
| }), | |
| ), | |
| ), | |
| }) | |
| function RouteComponent() { | |
| const search = Route.useSearch(); | |
| const { id } = Route.useParams(); | |
| const accountsQuery = useInfiniteQuery( | |
| fetchAccountsQueryOpts({ | |
| search, | |
| vaultId: id | |
| }) | |
| ); | |
| if (accountsQuery.isLoading) { | |
| // Handle loading here | |
| } | |
| return ( | |
| // page content | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment