ethanniser / next-typesafe-url

Fully typesafe, JSON serializable, and zod validated URL search params, dynamic route params, and routing for NextJS.
https://next-typesafe-url.dev
MIT License
362 stars 16 forks source link

Expose methods for manipulating search params #84

Open ericvoshall opened 7 months ago

ericvoshall commented 7 months ago

Hi, do you have any plans to expose any methods for manipulating the search params that leverages the schema defined for the route? I'm thinking mainly for updating params to reflect state of a page (current page of a table, applied filters, etc).

ethanniser commented 7 months ago

I'm not sure I understand sorry

Could you provide an example?

ericvoshall commented 7 months ago

It would be nice to have utilities to update the current search params. For example, using the below Route definition:

import { type DynamicRoute } from "next-typesafe-url";
import { z } from "zod";

const Route = {
  searchParams: z.object({
    page: z.number().min(1).catch(1),
    filters: z
      .object({
        name: z.string().optional(),
        email: z.string().email().optional(),
      })
      .optional(),
  }),
} satisfies DynamicRoute;
export type RouteType = typeof Route;

We can retrieve the validated search params (or an error) in the page by calling:

const searchParams = useSearchParams(Route.searchParams);

It would be nice to have something like:

const { searchParams, updateSearchParams } = useSearchParams(Route.searchParams);
const [page, setPage] = useState(searchParams.data.page);
const [filters, setFilters] = useState(searchParams.data.filters);

useEffect(() => updateSearchParams({ page, filters }), [page, filters]);
// ...

So if the searchParams reflect some sort of state in the page (the page of a table they're viewing, an email they've searched for, etc) there would also be a method for modifying them.

ethanniser commented 7 months ago

Thank you for the example I'll take a look when I get home. Feel free to ping me tomorrow if I forget to tonight.

lelabo-m commented 7 months ago

Could it be just a wrapper on useRouter and $path? The good thing about this would be that it will make sure people are using the library as intended. It seems trivial so I am not sure if it is a good addition but I kind of understand why people could ask for it.

kinsyudev commented 6 months ago

Just following up on this, I think it'd be an amazing addition to have this! Managing or reflecting state in the URL is a great way to create easily sharable / bookmarkable pages in applications where the user's interactions change the content of the page, think of an e-commerce page where the variant of a certain item is stored in the URL.