TanStackT
TanStack2mo ago
5 replies
continuing-aqua

Type inference doesn't seem to work with context and loader functions

Hiya, I'm getting the types of context and location inferred as {} in the following spot:
import { createFileRoute } from '@tanstack/react-router'
import NewsFeed from '../components/NewsFeed'
import { storiesQueryOptions } from '../queries'

type NewsSearchParams = {
  page?: number
}

export const Route = createFileRoute('/news')({
  validateSearch: (search: Record<string, unknown>): NewsSearchParams => {
    // validate and parse the search params into a typed state
    return {
      page: Number(search?.page ?? 1),
    }
  },
  loader: async ({ context, location }) => {
    // inference seems to fail here
    // @ts-expect-error Not sure why we are getting type errors here, it has something to do with the router module declaration
    await context.queryClient.ensureQueryData(storiesQueryOptions(location.search.page ?? 1))

  },
  component: News,
})

function News() {
  return (
    <NewsFeed />
  )
}

main.tsx looks like this:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider }  from '@tanstack/react-query'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import './index.css'
import { routeTree } from './routeTree.gen'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false, // default: true
    },
  },
})

const router = createRouter({
  routeTree,
  context: {
    queryClient,
  },
  defaultPreload: 'intent',
})

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router
  }
}



createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <RouterProvider router={router} />
    </QueryClientProvider>
  </StrictMode>,
)

I'm not sure what I'm doing wrong here.
Was this page helpful?