@excentone/spfx-react
Version:
Contains custom ReactJs components and hooks intended to use when developing SharePoint Framework (SPFx) Web components.
34 lines (32 loc) • 1.21 kB
JavaScript
import { useMemo, useRef } from "react";
/**
* `useQueryParams` provides a common interface for transforming query parameter values from string to a specific type.
* @param options The options to be passed to the custom hook.
* @returns An object containing the query parameter keys with the transformed values.
*/
export const useQueryParams = (options) => {
const opts = useRef({
...{ url: new URL(location.href), transform: {} },
...options
});
return useMemo(() => {
const { url, conversions } = opts.current;
const uri = typeof url === 'string' ? new URL(url) : url;
const qry = uri.searchParams;
const prm = {};
if (conversions)
Object
.keys(conversions)
.map((key) => {
const tff = conversions[key];
const val = qry.has(key) ? qry.get(key) : undefined;
prm[key] = tff ? tff(val) : val;
});
qry.forEach((val, key) => {
const tff = conversions ? conversions[key] : undefined;
prm[key] = tff ? tff(val) : val;
});
return prm;
}, []);
};
//# sourceMappingURL=useQueryParams.js.map