Merge pull request #1011 from LAION-AI/983-fix-locale-on-url-change

Update the locale cookie when a user sets the url manually
This commit is contained in:
AbdBarho
2023-01-30 18:41:54 +01:00
committed by GitHub
3 changed files with 77 additions and 32 deletions
@@ -1,13 +1,25 @@
import { Select } from "@chakra-ui/react";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { useCallback, useMemo } from "react";
import cookie from "react-cookies";
import { useCallback, useEffect, useMemo } from "react";
import { useCookies } from "react-cookie";
const LanguageSelector = () => {
const router = useRouter();
const [cookies, setCookie] = useCookies(["NEXT_LOCALE"]);
const { i18n } = useTranslation();
// Inspect the cookie based locale and the router based locale. If the user
// has manually set the locale via URL, they will differ. In that condition,
// update the cookie.
useEffect(() => {
const localeCookie = cookies["NEXT_LOCALE"];
const localeRouter = router.locale;
if (localeRouter !== localeCookie) {
setCookie("NEXT_LOCALE", localeRouter, { path: "/" });
}
}, [cookies, setCookie, router]);
// Memo the set of locales and their display names.
const localesAndNames = useMemo(() => {
return router.locales.map((locale) => ({
@@ -19,7 +31,7 @@ const LanguageSelector = () => {
const languageChanged = useCallback(
async (option) => {
const locale = option.target.value;
cookie.save("NEXT_LOCALE", locale, { path: "/" });
setCookie("NEXT_LOCALE", locale, { path: "/" });
const path = router.asPath;
return router.push(path, path, { locale });
},