ttrpg-tools/src/components/useNavigateWithParams.ts

22 lines
646 B
TypeScript

/**
* useNavigateWithParams — wraps navigate() to preserve the current URL
* search params (e.g. ?session=abc&player=alice) when navigating to a
* new path.
*/
import { useNavigate, useLocation } from "@solidjs/router";
export function useNavigateWithParams() {
const navigate = useNavigate();
const location = useLocation();
return (to: string) => {
// Split hash from the path so we can re-attach it after search params
const hashIdx = to.indexOf("#");
const path = hashIdx >= 0 ? to.slice(0, hashIdx) : to;
const hash = hashIdx >= 0 ? to.slice(hashIdx) : "";
navigate(path + location.search + hash);
};
}