UNPKG

next-query-params

Version:

Convenient state management of query parameters in Next.js apps.

70 lines (64 loc) 2.19 kB
import { useRouter } from 'next/router'; import { memo, useMemo } from '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 = 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); } var NextAdapter$1 = /*#__PURE__*/memo(NextAdapter); export { NextAdapter$1 as NextAdapter }; //# sourceMappingURL=next-query-params.esm.js.map