37 lines
928 B
TypeScript
37 lines
928 B
TypeScript
/** @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 [
|
|
string,
|
|
(to: string) => void
|
|
]
|
|
}
|