I am using below code for translation
in react application. its legacy application. so all of them are class
component and old libraries.
import i18next from 'i18next';
import React from 'react';
import TransFile from './TransFile.js';
const LanguageDetector = require('i18next-browser-languagedetector');
const initReactI18next = require('react-i18next');
var output;
//API call
apiDelegate.getTranslations().then((result) => {
output = JSON.stringify(result);
alert("output1 =>"+result);
});
alert("output2 is:"+output);
i18next
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: output, //Here I need to assign output
},
fallbackLng: 'fr',
});
i18next.changeLanguage(navigator.language);
alert("Output3 is:"+output);
export default i18next;
it is printing alert of output2
, then output3
then output1
. output2
and output1
are undefined
. I need to print them in order because I need to use API
data in my application. it is not assigning to actual variable
basically I need to assign the output
to my en
variable. below line in code
en: output,
I can not use async await
because babel
is not supporting
and its quite old application so when I update webpack gets failed.
apiDelegate
code.
getTranslations() {
var token = sessionStorage.getItem('jwt');
if (token == null) {
token = '';
}
return new Promise((resolve) => {
request
.get(baseUrl.api + '/file_download/en') //API call
.set({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
})
.then((value) => {
var result;
if (value.status === 200) {
result = value.body;
// alert(JSON.stringify(result));
}
resolve(result);
return result;
})
.catch((error) => {
var result;
if (error.status === 401 || error.status === 403) {
result = { status: -2, message: error, data: [] };
}
resolve(result);
});
});
}
can it be done using callback
or setTimeOut
? I know its basic but I am a beginner. not able to resolve the same. please help.
Edit1:- Data will be stored in the file or API output will be like below.
translation: {
app_header:"My contact",
app_address:"my address",
app_phone:"+1 93244 3223",
app_email:"abc@abc.com"
}
I am using i18 in my file like below.
import i18n from '../../../i18'
in component it will be used like below
i18n.t("app_header")
so value of app_header
will be replaced in app.