fix:language

This commit is contained in:
Rama Priyanto 2025-05-22 18:10:30 +07:00
parent 4382b55196
commit fb4b1f598b
1 changed files with 25 additions and 7 deletions

View File

@ -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<string>("");
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 (
<Select onValueChange={onSelectChange} defaultValue={localActive}>
<Select onValueChange={onSelectChange} value={selectedLang}>
<SelectTrigger className="w-[94px] border-none read-only:bg-transparent">
<SelectValue placeholder="Select a language" />
</SelectTrigger>