T
TanStack2y ago
crude-lavender

Save history for search params

I need to save the search parameters of a web page and use them when the user comes back to that page. For example, if the user is on "/routeA/?page=3" and then goes to "/routeB/?page=1", when they return to "/routeA", it should show the results for "page=3". How can I do this? I am uisng tanstack router
4 Replies
plain-purple
plain-purple2y ago
You can access it through useRouter().history
crude-lavender
crude-lavenderOP2y ago
How can I get it in the root component and navigate the user to that url rather than the default url
plain-purple
plain-purple2y ago
Can't you consume useRouter?
crude-lavender
crude-lavenderOP2y ago
So here is my current code
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ location, search }) => {
window.sessionStorage.setItem(`${location.pathname}:${appConstants.filterKeyName}`, JSON.stringify(search));


},
component: () => (
<>
....
{routes.map((route) => (
<Link
key={route.href}

to={route.href}
search={(prev) => {
let savedFilter = window.sessionStorage.getItem(`${route.href}:${appConstants.filterKeyName}`);
if (savedFilter) {
savedFilter = JSON.parse(savedFilter);
return savedFilter;
}
return prev;
}}
activeProps={{ className: 'dark:hover:text-gray-50 bg-gray-100 dark:bg-gray-800 font-semibold' }}
>
{route.icon} {route.displayName}
</Link>
))}
...
</>
),
});
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ location, search }) => {
window.sessionStorage.setItem(`${location.pathname}:${appConstants.filterKeyName}`, JSON.stringify(search));


},
component: () => (
<>
....
{routes.map((route) => (
<Link
key={route.href}

to={route.href}
search={(prev) => {
let savedFilter = window.sessionStorage.getItem(`${route.href}:${appConstants.filterKeyName}`);
if (savedFilter) {
savedFilter = JSON.parse(savedFilter);
return savedFilter;
}
return prev;
}}
activeProps={{ className: 'dark:hover:text-gray-50 bg-gray-100 dark:bg-gray-800 font-semibold' }}
>
{route.icon} {route.displayName}
</Link>
))}
...
</>
),
});
what I though of doing is to use this layout and store the histories in the sessionStorage but here is the problem. For some reason it always reverted to the default values mentioned in the validateSearchParams for each route this is not working as expected is there any better method than this? If its centralised it would be great. If you can point me to some examples it would be of huge help my main goal is if user was on routeA/?page=3 he went to routeB/?page=1 and routeC/?page=2 when he returns to the A, B and C routes he should be on the same page that means the queryParams should be the same. Thank you for your help

Did you find this page helpful?