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

Updating search params? #82

Closed ericvoshall closed 7 months ago

ericvoshall commented 7 months ago

Is there a preferred way of updating search params when using this library? I'd like to update search params based on a user's page in a table, filter options, etc.

lelabo-m commented 7 months ago

The docs say to use router.push on this page https://next-typesafe-url.dev/en/usage/routing.

I have done it myself like this:

import { useRouter } from "next/navigation";

export function Component() {
  const [searchQuery, setSearchQuery] = useState("");
  const router = useRouter();

  async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    e.preventDefault();

    setSearchQuery(e.target.value);

    router.push(
      $path({
        route: "/path",
        searchParams: { query: e.target.value},
      },
    );
  }

  return (
    <form>
      <input
        type="text"
        value={searchQuery}
        onChange={handleChange}
      />
    </form>
  );
}

However, in my example, I have not yet determined if we still need to use encodeURIComponent... I did not see any mention on the docs about the encoding of the URL parameters.

EDIT: Ok, I have an answer about encoding params. We can see in packages/next-typesafe-url/src/index.ts that $path calls methods from packages/next-typesafe-url/src/utils.ts which themselves use encodeURIComponent under the hood.

ericvoshall commented 7 months ago

I missed that line when looking over the docs, thank you! And thanks for the example.