Path: blob/1.0-develop/resources/scripts/plugins/useLocationHash.ts
7458 views
import { useLocation } from 'react-router';1import { useMemo } from 'react';23export default () => {4const location = useLocation();56const getHashObject = (value: string): Record<string, string> =>7value8.substring(1)9.split('&')10.reduce((obj, str) => {11const [key, value = ''] = str.split('=');1213return !str.trim() ? obj : { ...obj, [key]: value };14}, {});1516const pathTo = (params: Record<string, string>): string => {17const current = getHashObject(location.hash);1819for (const key in params) {20current[key] = params[key];21}2223return Object.keys(current)24.map((key) => `${key}=${current[key]}`)25.join('&');26};2728const hash = useMemo((): Record<string, string> => getHashObject(location.hash), [location.hash]);2930return { hash, pathTo };31};323334