languageController.jsx 1.65 KB
Newer Older
Muhammadali's avatar
Muhammadali committed
1 2 3 4 5 6 7
/** @format */
import React, { useEffect, useState } from 'react';
import { TranslationsProvider, useTranslator } from '@eo-locale/react';
const LanguageController = ({ children }) => {
	const [languageState, setLanguageState] = useState(null);
	const [messagesState, setMessagesState] = useState({});
	useEffect(() => {
Muhammadali's avatar
Muhammadali committed
8
		setLanguage('ru');
Muhammadali's avatar
Muhammadali committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	}, []);

	const locales = () => {
		return Object.entries(messagesState).map(
			([language, messages]) => ({ language, messages }),
			[],
		);
	};

	const getMessage = (key, options) => {
		// let resLang = this.messages[this.language][key] || key;
		let resLang = message[languageState][key] || key;

		if (options && Object.keys(options).length) {
			for (const lk of Object.keys(options)) {
				resLang = resLang.replaceAll(`{${lk}}`, options[lk]);
			}
		}
		return resLang;
	};

	const setLanguage = (lang) => {
		// this.language = lang;
		setLanguageState(lang);
		if (messagesState[lang]) {
			return;
		}
		return getMessages(lang).then((messages) => {
			// this.messages[lang] = messages;
			setMessagesState({ ...messagesState, [lang]: messages });
		});
	};

	const getMessages = (lang) => {
		switch (lang) {
			case 'ru':
				return import('../static/locale/ru.json');
Muhammadali's avatar
Muhammadali committed
46 47 48 49
			// case 'en':
			// 	return import('../static/locale/en.json');
			// case 'uz':
			// 	return import('../static/locale/uz.json');
Muhammadali's avatar
Muhammadali committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
			default:
				throw new Error('Language not supported');
		}
	};

	const onLangError = (e) => {
		console.debug(e.message);
	};

	return (
		<TranslationsProvider
			language={languageState}
			locales={locales()}
			onError={onLangError}>
			{children}
		</TranslationsProvider>
	);
};

export default LanguageController;