From fb4b1f598bc2a0249fb478dd83e7b5b9e00dc45c Mon Sep 17 00:00:00 2001 From: Rama Priyanto Date: Thu, 22 May 2025 18:10:30 +0700 Subject: [PATCH] fix:language --- .../partials/header/locale-switcher.tsx | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/components/partials/header/locale-switcher.tsx b/components/partials/header/locale-switcher.tsx index 8b295575..19d0d119 100644 --- a/components/partials/header/locale-switcher.tsx +++ b/components/partials/header/locale-switcher.tsx @@ -5,7 +5,7 @@ import { useParams } from "next/navigation"; import { locales } from "@/config"; import { usePathname, useRouter } from "@/i18n/routing"; -import { useEffect, useTransition } from "react"; +import { useEffect, useState, useTransition } from "react"; import { Select, SelectContent, @@ -16,33 +16,51 @@ import { import Image from "next/image"; import Cookies from "js-cookie"; +export const getLanguage = (): string | null => { + if (typeof window === "undefined") return null; + return localStorage.getItem("language"); +}; + +export const setLanguage = (value: string) => { + if (typeof window === "undefined") return; + localStorage.setItem("language", value); +}; + export default function LocalSwitcher() { const [isPending, startTransition] = useTransition(); const router = useRouter(); const pathname = usePathname(); const params = useParams(); const localActive = useLocale() || "in"; - const defaultLocale = Cookies.get("locale"); + const [selectedLang, setSelectedLang] = useState(""); useEffect(() => { - console.log("locale", defaultLocale); + const storedLang = getLanguage(); + + if (!storedLang) { + setLanguage("in"); + setSelectedLang("in"); - if (!defaultLocale) { - Cookies.set("locale", "in"); startTransition(() => { router.replace(pathname, { locale: "in" }); }); + } else { + setSelectedLang(storedLang); + startTransition(() => { + router.replace(pathname, { locale: storedLang }); + }); } }, []); const onSelectChange = (nextLocale: string) => { + setLanguage(nextLocale); + setSelectedLang(nextLocale); startTransition(() => { router.replace(pathname, { locale: nextLocale }); }); - Cookies.set("locale", nextLocale); }; return ( -