next-query-params
Version:
Convenient state management of query parameters in Next.js apps.
66 lines (63 loc) • 2.24 kB
JavaScript
import { useRouter } from 'next/router';
import { useMemo } from 'react';
var pathnameRegex = /(?:[\0-"\$->@-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+/;
function NextAdapterPages(_ref) {
var children = _ref.children,
_ref$shallow = _ref.shallow,
shallow = _ref$shallow === void 0 ? true : _ref$shallow;
var router = useRouter();
var match = router.asPath.match(pathnameRegex);
var pathname = match ? match[0] : router.asPath;
var location = useMemo(function () {
if (typeof window !== 'undefined') {
// For SSG, no query parameters are available on the server side,
// since they can't be known at build time. Therefore to avoid
// markup mismatches, we need a two-part render in this case that
// patches the client with the updated query parameters lazily.
// Note that for SSR `router.isReady` will be `true` immediately
// and therefore there's no two-part render in this case.
if (router.isReady) {
return window.location;
} else {
return {
search: ''
};
}
} else {
// On the server side we only need a subset of the available
// properties of `Location`. The other ones are only necessary
// for interactive features on the client.
return {
search: router.asPath.replace(pathnameRegex, '')
};
}
}, [router.asPath, router.isReady]);
var adapter = useMemo(function () {
function createUpdater(routeFn) {
return function updater(_ref2) {
var hash = _ref2.hash,
search = _ref2.search;
routeFn({
pathname: router.pathname,
search: search,
hash: hash
}, {
pathname: pathname,
search: search,
hash: hash
}, {
shallow: shallow,
scroll: false
});
};
}
return {
push: createUpdater(router.push),
replace: createUpdater(router.replace),
location: location
};
}, [location, pathname, router, shallow]);
return children(adapter);
}
export { NextAdapterPages as N };
//# sourceMappingURL=NextAdapterPages-293777d9.js.map