next-query-params
Version:
Convenient state management of query parameters in Next.js apps.
74 lines (66 loc) • 2.31 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var router = require('next/router');
var react = require('react');
var pathnameRegex = /(?:(?![#\?])[\s\S])+/;
function NextAdapter(_ref) {
var children = _ref.children,
_ref$shallow = _ref.shallow,
shallow = _ref$shallow === void 0 ? true : _ref$shallow;
var router$1 = router.useRouter();
var match = router$1.asPath.match(pathnameRegex);
var pathname = match ? match[0] : router$1.asPath;
var location = react.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$1.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$1.asPath.replace(pathnameRegex, '')
};
}
}, [router$1.asPath, router$1.isReady]);
var adapter = react.useMemo(function () {
function createUpdater(routeFn) {
return function updater(_ref2) {
var hash = _ref2.hash,
search = _ref2.search;
routeFn({
pathname: router$1.pathname,
search: search,
hash: hash
}, {
pathname: pathname,
search: search,
hash: hash
}, {
shallow: shallow,
scroll: false
});
};
}
return {
push: createUpdater(router$1.push),
replace: createUpdater(router$1.replace),
location: location
};
}, [location, pathname, router$1, shallow]);
return children(adapter);
}
var NextAdapter$1 = /*#__PURE__*/react.memo(NextAdapter);
exports.NextAdapter = NextAdapter$1;
//# sourceMappingURL=next-query-params.cjs.development.js.map