Repository navigation
Replies: 2 comments 1 reply
|
This happens because of how search middlewares run. When a link is built, the router collects the So on Option 1: give each section its own key (no custom code) // posts/route.tsx
validateSearch: z.object({ postsSearch: z.string().optional() }),
search: { middlewares: [retainSearchParams(['postsSearch'])] },
// users/route.tsx
validateSearch: z.object({ usersSearch: z.string().optional() }),
search: { middlewares: [retainSearchParams(['usersSearch'])] },A key list only copies those keys. Option 2: keep the same key, only retain when you're already inside the section Wrap the built-in middleware so it only runs when the current path is under the route's own path, and otherwise behaves as if there were no middleware: import { retainSearchParams, type SearchMiddleware } from '@tanstack/react-router'
function retainWithin<T extends object>(basePath: string): SearchMiddleware<T> {
const retain = retainSearchParams<T>(true)
return (ctx) => {
const path = window.location.pathname
const inside = path === basePath || path.startsWith(`${basePath}/`)
return inside ? retain(ctx) : ctx.next(ctx.search)
}
}
// users/route.tsx
search: { middlewares: [retainWithin('/users')] },
|
|
The middleware context is only // router-ref.ts
import type { AnyRouter } from '@tanstack/react-router'
let router: AnyRouter | undefined
export const setRouter = (r: AnyRouter) => { router = r }
export const isInside = (routeId: string) =>
router?.state.matches.some((m) => m.routeId === routeId) ?? false// retain-within.ts
import { retainSearchParams, type SearchMiddleware } from '@tanstack/react-router'
import { isInside } from './router-ref'
export function retainWithin<T extends object>(routeId: string): SearchMiddleware<T> {
const retain = retainSearchParams<T>(true)
return (ctx) => (isInside(routeId) ? retain(ctx) : ctx.next(ctx.search))
}// main.tsx
const router = createRouter({ routeTree })
setRouter(router)
// routes/posts/route.tsx
search: { middlewares: [retainWithin('/posts')] },
// routes/users/route.tsx
search: { middlewares: [retainWithin('/users')] },Result on @tanstack/react-router 1.170.39: This is client-side only: with SSR, the module-level ref would be shared between requests. If you want no module state at all, remove the middleware and set |
Uh oh!
There was an error while loading. Please reload this page.
Hi there,
I want to retain search parameters across navigations but only while navigating between a route and its descendants; I do not want the params to be retained between sibling routes, even if those routes have the same param name.
Example:
Any ideas on how to do this? Thanks!!
All reactions