From 354567cbf584639c83eca259d1eedf86c1774625 Mon Sep 17 00:00:00 2001 From: Christel Westerberg Date: Tue, 27 Aug 2024 16:09:36 +0200 Subject: [PATCH] fix: create useLazyPathname hook --- components/Current/Header/LoginButton.tsx | 10 +++++++--- utils/url.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/components/Current/Header/LoginButton.tsx b/components/Current/Header/LoginButton.tsx index 8634b71bc..86b66400f 100644 --- a/components/Current/Header/LoginButton.tsx +++ b/components/Current/Header/LoginButton.tsx @@ -1,6 +1,5 @@ "use client" -import { usePathname } from "next/navigation" import { PropsWithChildren, useEffect } from "react" import { login } from "@/constants/routes/handleAuth" @@ -9,6 +8,7 @@ import Link from "@/components/TempDesignSystem/Link" import { LinkProps } from "@/components/TempDesignSystem/Link/link" import useLang from "@/hooks/useLang" import { trackLoginClick } from "@/utils/tracking" +import { useLazyPathname } from "@/utils/url" import { TrackingPosition } from "@/types/components/tracking" @@ -25,7 +25,11 @@ export default function LoginButton({ color?: LinkProps["color"] }>) { const lang = useLang() - const pathName = usePathname() + const pathName = useLazyPathname() + + const href = pathName + ? `${login[lang]}?redirectTo=${encodeURIComponent(pathName)}` + : login[lang] useEffect(() => { document @@ -43,7 +47,7 @@ export default function LoginButton({ className={className} id={trackingId} color={color} - href={`${login[lang]}?redirectTo=${encodeURIComponent(pathName)}`} + href={href} prefetch={false} > {children} diff --git a/utils/url.ts b/utils/url.ts index 51ba2c52d..d33f8a7a8 100644 --- a/utils/url.ts +++ b/utils/url.ts @@ -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(null) + + useEffect(() => { + setUpdatedPathName(pathName) + }, [pathName]) + return updatedPathName ? updatedPathName : null +}