UNPKG

react-use

Version:
58 lines (57 loc) 2.16 kB
import { useEffect, useState } from 'react'; import { isClient, off, on } from './util'; var patchHistoryMethod = function (method) { var original = history[method]; history[method] = function (state) { var result = original.apply(this, arguments); var event = new Event(method.toLowerCase()); event.state = state; window.dispatchEvent(event); return result; }; }; if (isClient) { patchHistoryMethod('pushState'); patchHistoryMethod('replaceState'); } var useLocationServer = function () { return ({ trigger: 'load', length: 1, }); }; var buildState = function (trigger) { var state = history.state, length = history.length; var hash = location.hash, host = location.host, hostname = location.hostname, href = location.href, origin = location.origin, pathname = location.pathname, port = location.port, protocol = location.protocol, search = location.search; return { trigger: trigger, state: state, length: length, hash: hash, host: host, hostname: hostname, href: href, origin: origin, pathname: pathname, port: port, protocol: protocol, search: search, }; }; var useLocationBrowser = function () { var _a = useState(buildState('load')), state = _a[0], setState = _a[1]; useEffect(function () { var onPopstate = function () { return setState(buildState('popstate')); }; var onPushstate = function () { return setState(buildState('pushstate')); }; var onReplacestate = function () { return setState(buildState('replacestate')); }; on(window, 'popstate', onPopstate); on(window, 'pushstate', onPushstate); on(window, 'replacestate', onReplacestate); return function () { off(window, 'popstate', onPopstate); off(window, 'pushstate', onPushstate); off(window, 'replacestate', onReplacestate); }; }, []); return state; }; var hasEventConstructor = typeof Event === 'function'; export default isClient && hasEventConstructor ? useLocationBrowser : useLocationServer;