mirror of
https://github.com/supabase/supabase.git
synced 2026-10-06 18:05:11 +03:00
* Enhanced useHash.ts hook ^^ added dependencies, auto URL parsing rather than manually splitting it, lastly cleanup in useEffect! * Ran Prettier : ) * style: appease prettier --------- Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
37 lines
863 B
TypeScript
37 lines
863 B
TypeScript
import { useState, useCallback, useEffect } from 'react'
|
|
|
|
const useHash = () => {
|
|
const [hash, setHash] = useState(() => {
|
|
if (typeof window !== 'undefined') {
|
|
const url = new URL(window.location.href)
|
|
return url.hash.substring(1) // Removes the leading '#'
|
|
}
|
|
return undefined
|
|
})
|
|
|
|
const hashChangeHandler = useCallback(() => {
|
|
const url = new URL(window.location.href)
|
|
setHash(url.hash.substring(1))
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
window.addEventListener('hashchange', hashChangeHandler)
|
|
return () => {
|
|
window.removeEventListener('hashchange', hashChangeHandler)
|
|
}
|
|
}, [hashChangeHandler])
|
|
|
|
const updateHash = useCallback(
|
|
(newHash) => {
|
|
if (newHash !== hash) {
|
|
window.location.hash = newHash
|
|
}
|
|
},
|
|
[hash]
|
|
)
|
|
|
|
return [hash, updateHash] as const
|
|
}
|
|
|
|
export default useHash
|