2021-06-30 03:41:34 +02:00
|
|
|
import { useEffect } from 'react';
|
2020-09-09 05:46:31 +02:00
|
|
|
import { useDispatch, useSelector } from 'react-redux';
|
2020-09-20 10:33:39 +02:00
|
|
|
import { setLocale } from 'redux/actions/app';
|
2021-06-30 03:41:34 +02:00
|
|
|
import { useRouter } from 'next/router';
|
|
|
|
import { get, setItem } from 'lib/web';
|
2020-09-19 19:35:05 +02:00
|
|
|
import { LOCALE_CONFIG } from 'lib/constants';
|
2021-11-21 02:18:25 +01:00
|
|
|
import { getDateLocale, getTextDirection } from 'lib/lang';
|
2021-06-30 03:41:34 +02:00
|
|
|
import useForceUpdate from 'hooks/useForceUpdate';
|
|
|
|
import enUS from 'public/lang/en-US.json';
|
|
|
|
|
|
|
|
const messages = {
|
|
|
|
'en-US': enUS,
|
|
|
|
};
|
2020-09-09 05:46:31 +02:00
|
|
|
|
|
|
|
export default function useLocale() {
|
|
|
|
const locale = useSelector(state => state.app.locale);
|
|
|
|
const dispatch = useDispatch();
|
2021-06-30 03:41:34 +02:00
|
|
|
const { basePath } = useRouter();
|
|
|
|
const forceUpdate = useForceUpdate();
|
2021-11-21 02:18:25 +01:00
|
|
|
const dir = getTextDirection(locale);
|
|
|
|
const dateLocale = getDateLocale(locale);
|
2021-06-30 03:41:34 +02:00
|
|
|
|
|
|
|
async function loadMessages(locale) {
|
|
|
|
const { ok, data } = await get(`${basePath}/lang/${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
|
|
|
|
2020-09-19 19:35:05 +02:00
|
|
|
setItem(LOCALE_CONFIG, value);
|
2021-06-30 03:41:34 +02:00
|
|
|
|
|
|
|
if (locale !== value) {
|
|
|
|
dispatch(setLocale(value));
|
|
|
|
} else {
|
|
|
|
forceUpdate();
|
|
|
|
}
|
2020-09-09 05:46:31 +02:00
|
|
|
}
|
|
|
|
|
2021-06-30 03:41:34 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!messages[locale]) {
|
|
|
|
saveLocale(locale);
|
|
|
|
}
|
|
|
|
}, [locale]);
|
|
|
|
|
2021-11-21 02:18:25 +01:00
|
|
|
return { locale, saveLocale, messages, dir, dateLocale };
|
2020-09-09 05:46:31 +02:00
|
|
|
}
|