Skip to content

Instantly share code, notes, and snippets.

@jomifepe
Last active June 8, 2022 10:17
Show Gist options
  • Save jomifepe/ab56cd89c99602994df27692fd881caf to your computer and use it in GitHub Desktop.
Save jomifepe/ab56cd89c99602994df27692fd881caf to your computer and use it in GitHub Desktop.
useLocaleUpdates
import { useEffect, useState } from 'react';
import cookie from 'cookie';
import { useRouter } from 'next/router';
import { useTranslation } from 'react-i18next';
import usePrevious from './usePrevious';
import { LocaleDirection } from 'models/types';
import { getLocaleFromUrl, setLocaleCookie, updateLocale } from 'utils/locales';
import { COOKIE_LOCALE_KEY } from 'constants/cookies';
import { DEFAULT_LOCALE, LOCALES } from 'constants/locales';
/**
* Behavior of this hook:
* Checks a cookie to see if there's a locale already defined (this is also defined on the auth side)
* If there is, and if the locale wasn't overriden on the URL, updates the application language
* It uses the NEXT_LOCALE cookie, in order to avoid having "flashing" strings while changing
*/
const useLocaleUpdates = (): { direction: LocaleDirection } => {
const router = useRouter();
const { i18n } = useTranslation();
const [direction, setDirection] = useState<LocaleDirection>(null);
const previousLocale = usePrevious(router.locale);
useEffect(() => {
const urlLocale = getLocaleFromUrl();
if (!previousLocale && urlLocale) {
/* locale was overriden on the url */
const newDirection = i18n.dir(urlLocale);
setDirection(newDirection);
setLocaleCookie(urlLocale);
updateLocale(urlLocale as LOCALES, newDirection);
return;
}
const [newLocale, newDirection] = parseLocaleCookie();
setDirection(newDirection);
updateLocale(newLocale as LOCALES, newDirection);
if (newLocale !== router.locale) {
router.replace(router.asPath, router.asPath, { locale: newLocale });
}
}, [router.locale]);
const parseLocaleCookie = (): [string, LocaleDirection] => {
const cookieLocale: string = cookie.parse(window.document.cookie || '')[
COOKIE_LOCALE_KEY
];
if (!(cookieLocale && cookieLocale in LOCALES)) {
setLocaleCookie(DEFAULT_LOCALE);
return [router.locale, i18n.dir(router.locale)];
}
return [cookieLocale, i18n.dir(cookieLocale)];
};
return { direction };
};
export default useLocaleUpdates;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment