fix: create useLazyPathname hook

This commit is contained in:
Christel Westerberg
2024-08-27 16:09:36 +02:00
parent 2c6f43ef6c
commit 354567cbf5
2 changed files with 23 additions and 3 deletions

View File

@@ -1,3 +1,6 @@
import { usePathname } from "next/navigation"
import { useEffect, useState } from "react"
export function removeMultipleSlashes(str: string) {
return str.replaceAll(/\/\/+/g, "/")
}
@@ -9,3 +12,16 @@ export function removeTrailingSlash(pathname: string) {
}
return pathname
}
/*** This hook is used to get the current pathname (as reflected in window.location.href) of the page. During ssr, the value from usePathname()
* is the value return from NextResponse.rewrite() (e.g. the path from the app directory) instead of the actual pathname from the URL.
*/
export function useLazyPathname() {
const pathName = usePathname()
const [updatedPathName, setUpdatedPathName] = useState<string | null>(null)
useEffect(() => {
setUpdatedPathName(pathName)
}, [pathName])
return updatedPathName ? updatedPathName : null
}