Skip to content

Commit

Permalink
feat(use-hash-param): implement
Browse files Browse the repository at this point in the history
  • Loading branch information
megheaiulian committed Feb 28, 2022
1 parent 6231161 commit 4026c08
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/use-hash-param.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useState, useEffect, useMemo } from 'haunted';

const hashUrl = () =>
new URL(
location.hash.replace(/^#!?/iu, '').replace('%23', '#'),
location.origin
),
parameterize = (hashParam) =>
hashParam
? () =>
new URLSearchParams(hashUrl().hash.replace('#', '')).get(hashParam)
: undefined;

export const link = (hashParam, value) => {
if (!hashParam) {
return;
}
const url = hashUrl(),
sp = new URLSearchParams(url.hash.replace('#', ''));
sp.set(hashParam, value);
return (
'#!' + Object.assign(url, { hash: sp }).href.replace(location.origin, '')
);
},
useHashParam = (hashParam) => {
const parameterized = useMemo(() => parameterize(hashParam), [hashParam]),
[param, setParam] = useState(parameterized);

useEffect(() => {
if (parameterized == null) {
return;
}
const readParam = () =>
requestAnimationFrame(() => setParam(parameterized));
readParam();
window.addEventListener('popstate', readParam);
window.addEventListener('hash-changed', readParam);
return () => {
window.removeEventListener('popstate', readParam);
window.removeEventListener('hash-changed', readParam);
};
}, [parameterized]);

return param;
};

0 comments on commit 4026c08

Please sign in to comment.