useState like API for manipulating single search param in the URL #70
uchihamalolan
started this conversation in
Ideas
Replies: 3 comments 7 replies
-
You can build this tiny custom hook yourself with the useSearch and useNavigate hooks. Have you tried that? |
Beta Was this translation helpful? Give feedback.
1 reply
-
It’s all about how opinionated it is. If it’s very primitive and low level I might consider adding it to the library. If it’s relatively primitive, official docs for sure. We’ll see!
…On Nov 16, 2021, 6:51 PM -0700, Malolan B ***@***.***>, wrote:
Sure, I'll try that. Do you think it'll be useful addition to the examples in the docs?
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or unsubscribe.
Triage notifications on the go with GitHub Mobile for iOS or Android.
|
Beta Was this translation helpful? Give feedback.
1 reply
-
Not sure if this ever made its way in, but this is what I've been using. import {
type AnyRoute,
type RegisteredRouter,
type RouteById,
type RouteIds,
useNavigate,
useSearch,
} from "@tanstack/react-router";
import type { UseSearchOptions } from "@tanstack/react-router/dist/esm/useSearch";
import type { Expand } from "@tanstack/react-router/dist/esm/utils";
import { useCallback } from "react";
export function useSearchParam<
TRouteTree extends AnyRoute = RegisteredRouter["routeTree"],
TFrom extends RouteIds<TRouteTree> = RouteIds<TRouteTree>,
TSearch = Expand<RouteById<TRouteTree, TFrom>["types"]["fullSearchSchema"]>,
TSelected = TSearch,
Key extends keyof TSelected = keyof TSelected,
>(props: {
from: UseSearchOptions<TFrom, true, TSearch, TSelected>["from"];
searchKey: Key;
replace?: boolean;
}) {
const value = useSearch<TRouteTree, TFrom, true, TSearch, TSelected>({
from: props.from,
})[props.searchKey];
const navigate = useNavigate({ from: props.from });
type Value = typeof value;
const update = useCallback(
(nextOrUpdateFromLast: Value | ((last: Value) => Value)) => {
navigate({
search: (last) => {
const next =
nextOrUpdateFromLast instanceof Function
? nextOrUpdateFromLast(last[props.searchKey] as any)
: nextOrUpdateFromLast;
return { ...last, [props.searchKey]: next };
},
replace: props.replace,
});
},
[navigate, props.replace, props.searchKey],
);
return [value, update] as const;
} Looks like so: const [categoryId, setCategoryId] = useSearchParam({
from: Route.fullPath,
searchKey: "categoryId",
replace: true,
}); I'd be happy to create a PR if this is something you'd want in the library. |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Like:
setParam
to update the URL and trigger re-renderBeta Was this translation helpful? Give feedback.
All reactions