amannn / next-query-params

Convenient state management of query parameters in Next.js apps
Other
164 stars 12 forks source link

Nextjs13 support #26

Closed ronalterya closed 1 year ago

ronalterya commented 1 year ago

I would like this lib to work in client component using next/navigation

amannn commented 1 year ago

If someone wants to make a PR for this that includes tests, I'd be happy to review it!

mike667 commented 1 year ago

Here is my adapter for Next.js 13.4 (app folder)

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo } from "react";
import { PartialLocation, QueryParamAdapterComponent } from "use-query-params";

export const NextQueryParamAdapter: QueryParamAdapterComponent = ({
  children,
}) => {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const adapter = useMemo(() => {
    return {
      replace(location: PartialLocation) {
        router.replace(pathname + location.search);
      },
      push(location: PartialLocation) {
        router.push(pathname + location.search);
      },
      get location() {
        return {
          search: searchParams.toString(),
        };
      },
    };
  }, [router, pathname, searchParams]);

  return children(adapter);
};
amannn commented 1 year ago

Hey @mike667, thanks for sharing your implementation! I've created a PR based on this and also included support for location hashes.