"use client"; import { useCallback, useEffect, useRef } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; /** * Replaces react-router-dom's `useSearchParams` for the ported feature pages * (members, reports): filter/sort/pagination state lives in the URL so a * filtered view stays shareable and survives reload (see each page's own * comments). The tuple shape mirrors react-router's closely enough that * porting a page off it only needed this hook swapped in, plus dropping the * `{ replace: true }` second argument react-router's setter took (this * always replaces, matching how every call site here used it). * * The setter builds on the last query string this hook wrote, not the params * of the last render: `router.replace` lands later, so two updates before the * next render (or a debounced callback holding an old setter) would otherwise * start from stale params and drop the first change. The pending write is * shared (module level) because every instance on a page writes the same URL. * A rendered URL this hook never sent is an outside navigation, which wins. */ let pending: { path: string; qs: string; sent: Set } | null = null; export function useQueryState(): [ URLSearchParams, (updater: (prev: URLSearchParams) => URLSearchParams) => void, ] { const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); const rendered = searchParams.toString(); const latest = useRef(rendered); useEffect(() => { latest.current = rendered; if (pending && (pending.path !== pathname || pending.qs === rendered || !pending.sent.has(rendered))) pending = null; }, [pathname, rendered]); const setSearchParams = useCallback( (updater: (prev: URLSearchParams) => URLSearchParams) => { const base = pending?.path === pathname ? pending.qs : latest.current; const qs = updater(new URLSearchParams(base)).toString(); // Only clear when the write matches what is rendered (nothing left waiting to render); a no-op relative to a pending base must keep that pending change. const sent = new Set(pending?.path === pathname ? pending.sent : []).add(latest.current).add(qs); pending = qs === latest.current ? null : { path: pathname, qs, sent }; router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false }); }, [router, pathname], ); return [searchParams, setSearchParams]; }