Skip to content

Commit

Permalink
fix: πŸ› make useLocation work on server, improve hook
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Apr 9, 2019
1 parent 5bd194f commit 6f6030a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 51 deletions.
12 changes: 9 additions & 3 deletions src/__stories__/useLocation.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<pre>
{JSON.stringify(state, null, 2)}
</pre>
<div>
<button onClick={() => go('page-1')}>Page 1</button>
<button onClick={() => go('page-2')}>Page 2</button>
<pre>
{JSON.stringify(state, null, 2)}
</pre>
</div>
);
};

Expand Down
92 changes: 44 additions & 48 deletions src/useLocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,57 +36,53 @@ export interface LocationSensorState {
search?: string;
}

const useLocation = (): LocationSensorState => {
const buildState = (trigger: string) => {
const {
state,
length
} = history;

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 useLocationServer = (): LocationSensorState => ({
trigger: 'load',
length: 1,
});

const buildState = (trigger: string) => {
const {
state,
length
} = history;

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);
Expand All @@ -101,4 +97,4 @@ const useLocation = (): LocationSensorState => {
return state;
};

export default useLocation;
export default isClient ? useLocationBrowser : useLocationServer;

0 comments on commit 6f6030a

Please sign in to comment.