UNPKG

recoil-sync-next

Version:

recoil-sync stores for Next.js

48 lines (47 loc) 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useSyncURLNext = void 0; const router_1 = require("next/router"); const react_1 = require("react"); function useSyncURLNext() { const { isReady, asPath, replace, push, events } = (0, router_1.useRouter)(); const urlRef = (0, react_1.useRef)({ path: isReady ? asPath : '/', needNotify: !isReady, handler: undefined, }); const { needNotify, handler } = urlRef.current; (0, react_1.useEffect)(() => { if (isReady && needNotify && handler) { urlRef.current.path = asPath; urlRef.current.needNotify = false; handler(); } }, [isReady, needNotify, handler, asPath]); const updateURL = (0, react_1.useCallback)((url) => { urlRef.current.path = url; }, []); const browserInterface = { replaceURL: (0, react_1.useCallback)((url) => replace(url, undefined, { shallow: true }), [replace]), pushURL: (0, react_1.useCallback)((url) => push(url, undefined, { shallow: true }), [push]), getURL: (0, react_1.useCallback)(() => { var _a, _b, _c; const url = new URL(urlRef.current.path, (_c = (_b = (_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.href) !== null && _c !== void 0 ? _c : 'http://localhost:3000'); return url.toString(); }, []), listenChangeURL: (0, react_1.useCallback)((handler) => { urlRef.current.handler = handler; events.on('routeChangeStart', updateURL); events.on('routeChangeStart', handler); return () => { events.off('routeChangeStart', handler); events.off('routeChangeStart', updateURL); urlRef.current.handler = undefined; }; }, [events, updateURL]), }; return { browserInterface, }; } exports.useSyncURLNext = useSyncURLNext;