react-router-typesafe-routes
Version:
Enhanced type safety via validation for all route params in React Router v7.
34 lines (33 loc) • 2.01 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTypedSearchParams = void 0;
const react_router_1 = require("react-router");
const react_1 = require("react");
function useTypedSearchParams(route, typedDefaultInit) {
const defaultInit = (0, react_1.useMemo)(() => (typedDefaultInit ? route.$serializeSearchParams({ searchParams: typedDefaultInit }) : undefined), [route, typedDefaultInit]);
const [searchParams, setSearchParams] = (0, react_router_1.useSearchParams)(defaultInit);
const typedSearchParams = (0, react_1.useMemo)(() => route.$deserializeSearchParams(searchParams), [route, searchParams]);
const setTypedSearchParams = (0, react_1.useCallback)((params, _a = {}) => {
var { state, untypedSearchParams } = _a, restNavigateOptions = __rest(_a, ["state", "untypedSearchParams"]);
setSearchParams((prevParams) => {
return route.$serializeSearchParams({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
searchParams: typeof params === "function" ? params(route.$deserializeSearchParams(prevParams)) : params,
untypedSearchParams: untypedSearchParams ? prevParams : undefined,
});
}, Object.assign(Object.assign({}, (state ? { state: route.$buildState({ state }) } : {})), restNavigateOptions));
}, [route, setSearchParams]);
return [typedSearchParams, setTypedSearchParams];
}
exports.useTypedSearchParams = useTypedSearchParams;
;