How to use navigate but keep prev search params? #3345
Replies: 4 comments 7 replies
-
Beta Was this translation helpful? Give feedback.
-
what does that mean? can you please provide a complete minimal example by forking one of the existing stackblitz examples and provide exact steps that a user would perform? |
Beta Was this translation helpful? Give feedback.
-
Hello @ruiaraujo012 , i think you can use this hook import { createFileRoute, Link, useRouter } from '@tanstack/react-router';
export const Route = createFileRoute('/users/$userId')({
component: RouteComponent,
});
function RouteComponent() {
const router = useRouter();
return (
<div>
Hello "/users/$userId"!
<hr />
{/* <Link to="..">Back (Here is the "problem")</Link> */}
<button type="button" onClick={() => router.history.back()}>
Back (Here is the "problem")
</button>
</div>
);
} https://stackblitz.com/edit/tanstack-router-s8vvv8zu?file=src%2Froutes%2Fusers%2F%24userId.tsx |
Beta Was this translation helpful? Give feedback.
-
I have some breadcrumbs in my application, and to make my back button did this: const handleGoBack = () => {
if (breadcrumbs.length > 1) {
if (history.canGoBack()) {
history.back();
return;
}
}
const path = breadcrumbs[breadcrumbs.length - 2]?.path;
if (path) {
navigate({
to: path,
});
}
}; So if I can go back, I do, if not I use from my breadcrumbs: import { useMatches } from "@tanstack/react-router";
import { useMemo } from "react";
export type BreadcrumbItemType = {
title: string;
path: string;
disabled?: boolean;
};
const breadcrumbsLabelMap = new Map<string, BreadcrumbItemType>([
["/", { title: "Relatórios", path: "/" }],
["/registers", { title: "Cadastros", path: "/registers/", disabled: true }],
["/registers/customers", { title: "Clientes", path: "/registers/customers" }],
[
"/registers/contracts",
{
title: "Contratos",
path: "/registers/contracts",
},
],
[
"/users",
{
title: "Usuários",
path: "/users",
},
],
[
"/users/create",
{
title: "Novo usuário",
path: "/users/create",
},
],
[
"/users/$userId",
{
title: "Editar usuário",
path: "/users/$userId",
},
],
]);
function normalizePath(pathname: string): string {
if (pathname === "/") return pathname;
return pathname.endsWith("/") ? pathname : `${pathname}`;
}
export function useGetBreadcrumbs() {
const matches = useMatches();
const breadcrumbs = useMemo(() => {
if (!matches || matches.length === 0) return [];
const currentMatch = matches[matches.length - 1];
console.log(currentMatch);
const result: BreadcrumbItemType[] = [];
const pathname = currentMatch.pathname;
const splittedPath = pathname.split("/").filter(Boolean);
if (splittedPath.length === 0) {
const loaderData = currentMatch.loaderData as { title?: string };
if (loaderData?.title) {
result.push({ title: loaderData.title, path: "/", disabled: false });
} else {
result.push({ title: "Relatórios", path: "/", disabled: false });
}
return result;
}
for (let i = 1; i <= splittedPath.length; i++) {
const path = `/${splittedPath.slice(0, i).join("/")}`;
const normalizedPath = normalizePath(path);
const loaderData = currentMatch.loaderData as { title?: string };
const mapEntry = breadcrumbsLabelMap.get(normalizedPath);
let breadcrumbItem: BreadcrumbItemType | undefined;
if (loaderData?.title && i === splittedPath.length) {
breadcrumbItem = {
title: loaderData.title,
path: normalizedPath,
disabled: mapEntry?.disabled ?? false,
};
} else if (mapEntry) {
breadcrumbItem = mapEntry;
}
if (breadcrumbItem) {
result.push(breadcrumbItem);
}
}
return result;
}, [matches]);
return breadcrumbs;
} Maybe you can check somehow if you are going back from users or another context, split your full path and check the conditions to use history.back or no. Hope I could help you. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
Let's assume the following routes:
/users
/users/$userId
/notifications
I need to implement a back button, so the user could navigate back in the app. To go from
/users/1
I could use aLink
ornavigate
withto='..'
, and it works, but, if I have search params, those will be lost in the process, for example:/users?page=5&size=10
I select one user and navigate to/users/273
/users?page=0&size=10
(search params reset to default ones)I could use
history.back()
, although, if I came from/notifications
I don't want to go back there, but to/users?page=0&size=10
How can I solve this? Is there any way of knowing the
from
route so I could usehistory.back()
orto='..'
conditionally?Here is the example https://stackblitz.com/edit/tanstack-router-8jslocus?file=src%2Froutes%2Fusers%2F%24userId.tsx
Steps:
Next
a couple of times (like page=3)Navigate example to some user
Back
(prev search was lost, I could usehistory.back()
, but...)here
Back
(this back should go tousers
with the default search)So I wanted to conditionally use
history.back()
or navigateto='..'
based on the last route, if users, go back to preserve search, otherwise, use theto
option.Beta Was this translation helpful? Give feedback.
All reactions