diff --git a/src/__stories__/useLocation.story.tsx b/src/__stories__/useLocation.story.tsx index f133b586..9784f2d2 100644 --- a/src/__stories__/useLocation.story.tsx +++ b/src/__stories__/useLocation.story.tsx @@ -3,13 +3,19 @@ import {storiesOf} from '@storybook/react'; import {useLocation} from '..'; import ShowDocs from './util/ShowDocs'; +const go = (page) => history.pushState({}, '', page); + const Demo = () => { const state = useLocation(); return ( -
-      {JSON.stringify(state, null, 2)}
-    
+
+ + +
+        {JSON.stringify(state, null, 2)}
+      
+
); }; diff --git a/src/useLocation.ts b/src/useLocation.ts index 68389d81..5717ef44 100644 --- a/src/useLocation.ts +++ b/src/useLocation.ts @@ -36,57 +36,53 @@ export interface LocationSensorState { search?: string; } -const useLocation = (): LocationSensorState => { - const buildState = (trigger: string) => { - const { - state, - length - } = history; +const useLocationServer = (): LocationSensorState => ({ + trigger: 'load', + length: 1, +}); - const { - hash, - host, - hostname, - href, - origin, - pathname, - port, - protocol, - search - } = location; +const buildState = (trigger: string) => { + const { + state, + length + } = history; - return { - trigger, - state, - length, - hash, - host, - hostname, - href, - origin, - pathname, - port, - protocol, - search - }; + const { + hash, + host, + hostname, + href, + origin, + pathname, + port, + protocol, + search + } = location; + + return { + trigger, + state, + length, + hash, + host, + hostname, + href, + origin, + pathname, + port, + protocol, + search }; +}; - const [state, setState] = useState(isClient - ? buildState('load') - : { - trigger: 'load', - length: 1 - } - ); - - const onChange = (trigger: string) => - setState(buildState(trigger)); - - const onPopstate = () => onChange('popstate'); - const onPushstate = () => onChange('pushstate'); - const onReplacestate = () => onChange('replacestate'); +const useLocationBrowser = (): LocationSensorState => { + const [state, setState] = useState(buildState('load'));; useEffect(() => { + const onPopstate = () => setState(buildState('popstate')); + const onPushstate = () => setState(buildState('pushstate')); + const onReplacestate = () => setState(buildState('replacestate')); + on(window, 'popstate', onPopstate); on(window, 'pushstate', onPushstate); on(window, 'replacestate', onReplacestate); @@ -101,4 +97,4 @@ const useLocation = (): LocationSensorState => { return state; }; -export default useLocation; +export default isClient ? useLocationBrowser : useLocationServer;