Skip to content

Commit

Permalink
feat: 🎸 add useSearchParam() hook
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Sep 1, 2019
1 parent 1646ecf commit b22f32f
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/__stories__/useSearchParam.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useSearchParam } from '..';
import ShowDocs from './util/ShowDocs';

const Demo = () => {
const foo = useSearchParam('foo');

return (
<div>
<div>foo: {foo || '🤷‍♂️'}</div>
<div>
<button onClick={() => history.pushState({}, '', location.pathname + '?foo=bar')}>foo: bar</button>
</div>
<div>
<button onClick={() => history.pushState({}, '', location.pathname + '?foo=baz')}>foo: baz</button>
</div>
<div>
<button onClick={() => history.pushState({}, '', location.pathname)}>delete</button>
</div>
</div>
);
};

storiesOf('Sensors|useSearchParam', module)
// .add('Docs', () => <ShowDocs md={require('../../docs/useQueryParam.md')} />)
.add('Demo', () => <Demo />);
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export { default as useRafLoop } from './useRafLoop';
* @deprecated This hook is obsolete, use `useMountedState` instead
*/
export { default as useRefMounted } from './useRefMounted';
export { default as useSearchParam } from './useSearchParam';
export { default as useScroll } from './useScroll';
export { default as useScrolling } from './useScrolling';
export { default as useSessionStorage } from './useSessionStorage';
Expand Down
29 changes: 29 additions & 0 deletions src/useSearchParam.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useState, useEffect } from 'react';

const getValue = (search: string, param: string) => new URLSearchParams(search).get(param);

export type UseQueryParam = (param: string) => string | null;

const useSearchParam: UseQueryParam = param => {
const [value, setValue] = useState<string | null>(() => getValue(location.search, param));

useEffect(() => {
const onChange = () => {
setValue(getValue(location.search, param));
};

window.addEventListener('popstate', onChange);
window.addEventListener('pushstate', onChange);
window.addEventListener('replacestate', onChange);

return () => {
window.removeEventListener('popstate', onChange);
window.removeEventListener('pushstate', onChange);
window.removeEventListener('replacestate', onChange);
};
}, []);

return value;
};

export default useSearchParam;

0 comments on commit b22f32f

Please sign in to comment.