I am using react i8next and using it to translate from English to arabic with react large app in our app we have a module we created and it is called authnection module and it has it is own ui and it is own translation.json files
I have created a custom hook that takes every separate module i8next config , and init the i8next inside this custom hook the problem that when user click on button to change language the app goes inside infinite loop and language not changed till I make refresh
my basic i8next config
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from 'i18next-http-backend';
const config = {
supportedLngs: ['en', 'ar'],
fallbackLng: "en",
detection: {
order: ['subdomain', 'path', 'cookie', 'htmlTag'],
caches: ['cookie'],
},
resources: {
},
react: { useSuspense: true },
}
function init(config: any) {
i18next
.use(initReactI18next) // passes i18n down to react-i18next
.use(LanguageDetector)
.init(config)
console.log("inited")
return i18next;
}
i18next
.use(initReactI18next) // passes i18n down to react-i18next
.use(LanguageDetector)
.init(config)
export default i18next;
my-custom hook code
import { useEffect, useState } from "react"
import i18next from "../config/translate"
import { useTranslation } from "react-i18next"
export const useTranslator = (resources?: any) => {
// @ts-ignore(resources)
i18next.init(resources)
// i18next.createInstance(resources)
const { t, } = useTranslation()
const [currentLang, setCurrentLang] = useState(i18next.language)
useEffect(() => {
document.body.dir = i18next.dir(currentLang)
console.log(i18next);
// setCurrentLang(i18next.language)
}, [currentLang])
return {
t,
currentLang,
i18next
// lang, setLang, url, changeLanguage, t
}
}
the component that uses the custom hook and add it is own config
const resources = {
en: {
translation: enTrans
},
ar: {
translation: arTrans
}
}
const config = {
supportedLngs: ['en', 'ar'],
resources,
fallbackLng: "en",
detection: {
order: ['subdomain', 'path', 'cookie', 'htmlTag'],
caches: ['cookie'],
},
react: { useSuspense: true },
}
const { t } = useTranslator(config)
useEffect(() => {
console.log("renderdcx");
}, [])
return (
<>
<h1> Errors : {error} </h1>
<h1> {t("login.name")}: {displayName}</h1>
<h1> {t("login.email")}: {email} </h1>
</>
)