2022-06-20 17:19:40 +00:00
|
|
|
import { useLocation } from 'react-router';
|
|
|
|
import { useMemo } from 'react';
|
|
|
|
|
|
|
|
export default () => {
|
|
|
|
const location = useLocation();
|
|
|
|
|
|
|
|
const getHashObject = (value: string): Record<string, string> =>
|
|
|
|
value
|
|
|
|
.substring(1)
|
|
|
|
.split('&')
|
|
|
|
.reduce((obj, str) => {
|
2022-11-25 20:25:03 +00:00
|
|
|
const [key = '', value = ''] = str.split('=');
|
2022-06-20 17:19:40 +00:00
|
|
|
|
|
|
|
return !str.trim() ? obj : { ...obj, [key]: value };
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
const pathTo = (params: Record<string, string>): string => {
|
|
|
|
const current = getHashObject(location.hash);
|
|
|
|
|
|
|
|
for (const key in params) {
|
2022-11-25 20:25:03 +00:00
|
|
|
current[key] = params[key] ?? '';
|
2022-06-20 17:19:40 +00:00
|
|
|
}
|
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
return Object.keys(current)
|
2022-11-25 20:25:03 +00:00
|
|
|
.map(key => `${key}=${current[key]}`)
|
2022-06-26 19:13:52 +00:00
|
|
|
.join('&');
|
2022-06-20 17:19:40 +00:00
|
|
|
};
|
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
const hash = useMemo((): Record<string, string> => getHashObject(location.hash), [location.hash]);
|
2022-06-20 17:19:40 +00:00
|
|
|
|
|
|
|
return { hash, pathTo };
|
|
|
|
};
|