TanStackT
TanStack3mo ago
49 replies
popular-magenta

Router + Query integration // route invalidation

I'm torn between 2 things:

loaderDeps = ({ search }) => search,
loader: ({ context: { queryClient }, deps, params }) => 
  queryClient.ensureQueryData({
    queryKey: [params, deps],
    queryFn: () => fetch(`/api/${params}?${deps}`) // pardon me here, i'm lazy to code all
 })


then either:

function Component() {
  const data = Route.useLoaderData()
}


which is extremely simple, does not need any loading management of any kind but needs double cache invalidation:

await router.invalidate({ filter: ({ routePath }) => routePath = '/xxx' })
await queryClient.invalidateQueries({ queryKey: ['/xxx'] })


or:

function Component() {
  const params = Route.useParams()
  const search = Route.useSearch()
  
  const { data } = useSuspenseQuery({
    queryKey: [params, deps],
    queryFn: () => fetch(`/api/${params}?${deps}`) // pardon me here, i'm lazy to code all
 })    
}


where there's no double cache invalidation needed, but a double api declaration (the query options in both loader and useSuspenseQuery)

what i could see as a workaround is:

function createQuery(params: any, search: any) {
  return {
    queryKey: [],
    queryFn: async () => {}
  }
}

// then
loader: ({ context: { queryClient }, deps, params }) => 
  queryClient.ensureQueryData(createQuery(params, deps))

// and
function Component() {
  const params = Route.useParams()
  const search = Route.useSearch()
  
  const { data } = useSuspenseQuery(createQuery(params, search))    
}


but i don't know how to type params and
search
. I have tried ReturnType<(typeof Route)['useParams']> but it returns
any
😄

...and it's still not as appealing DX as the very 1st one, which only have an issue of route caching data on top of react-query caching data (and subscriptions)

please advice 🙏
Was this page helpful?