umami/hooks/useLocale.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

import { useEffect } from 'react';
import { useRouter } from 'next/router';
2022-08-29 05:20:54 +02:00
import { get, setItem } from 'next-basics';
import { LOCALE_CONFIG } from 'lib/constants';
2021-11-21 02:18:25 +01:00
import { getDateLocale, getTextDirection } from 'lib/lang';
import useStore, { setLocale } from 'store/app';
import useForceUpdate from 'hooks/useForceUpdate';
2022-03-19 03:17:23 +01:00
import enUS from 'public/intl/messages/en-US.json';
const messages = {
'en-US': enUS,
};
2020-09-09 05:46:31 +02:00
const selector = state => state.locale;
2020-09-09 05:46:31 +02:00
export default function useLocale() {
const locale = useStore(selector);
const { basePath } = useRouter();
const forceUpdate = useForceUpdate();
2021-11-21 02:18:25 +01:00
const dir = getTextDirection(locale);
const dateLocale = getDateLocale(locale);
async function loadMessages(locale) {
2022-03-19 03:17:23 +01:00
const { ok, data } = await get(`${basePath}/intl/messages/${locale}.json`);
if (ok) {
messages[locale] = data;
}
}
async function saveLocale(value) {
if (!messages[value]) {
await loadMessages(value);
}
2020-09-09 05:46:31 +02:00
setItem(LOCALE_CONFIG, value);
if (locale !== value) {
setLocale(value);
} else {
forceUpdate();
}
2020-09-09 05:46:31 +02:00
}
useEffect(() => {
if (!messages[locale]) {
saveLocale(locale);
}
}, [locale]);
useEffect(() => {
const url = new URL(window.location.href);
const locale = url.searchParams.get('locale');
if (locale) {
saveLocale(locale);
}
}, []);
2021-11-21 02:18:25 +01:00
return { locale, saveLocale, messages, dir, dateLocale };
2020-09-09 05:46:31 +02:00
}