graphicek/client/src/utils/hooks/useHashLocation.ts

34 lines
896 B
TypeScript
Raw Normal View History

2022-08-28 11:56:03 +02:00
/** @source wouter example */
import { useState, useEffect } from 'preact/hooks'
// (excluding the leading '#' symbol)
const currentLocation = () => {
return window.location.hash.replace(/^#/, '') || '/'
}
const navigate = (to: string) => (window.location.hash = to)
export const useHashLocation = () => {
const [loc, setLoc] = useState(currentLocation())
useEffect(() => {
// this function is called whenever the hash changes
const handler = () => setLoc(currentLocation())
// subscribe to hash changes
window.addEventListener('hashchange', handler)
return () => window.removeEventListener('hashchange', handler)
}, [])
return [loc, navigate] as const
}
export const useHashRouterLocation = () => {
const [location, setLocation] = useHashLocation()
const locationWithoutQueryString = location.split('?')[0]
return [locationWithoutQueryString, setLocation] as const
2022-08-28 11:56:03 +02:00
}