Reputation: 3990
I am trying to use a custom i18n setup but it's says undefined, but when I print the object has the values, how can this be solved.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import backend from 'i18next-http-backend';
i18n
.use(backend)
.use(initReactI18next)
.init({
lng: window.location.pathname.split('/')[1] !== 'en' ? 'de' : 'en',
fallbackLng: 'de',
whitelist: ['en', 'de'],
debug: process.env.NODE_ENV === 'development',
backend: {
loadPath:
process.env.NODE_ENV === 'development'
? '/locales/{{lng}}/{{ns}}.json'
: '/static/locales/{{lng}}/{{ns}}.json',
addPath:
process.env.NODE_ENV === 'development'
? '/locales/add/{{lng}}/{{ns}}.json'
: '/static/locales/add/{{lng}}/{{ns}}.json',
crossDomain: true,
},
ns: 'translations',
defaultNS: 'translations',
interpolation: {
escapeValue: false,
formatSeparator: undefined,
unescapePrefix: undefined,
nestingOptionsSeparator: undefined,
},
keySeparator: false,
nsSeparator: false,
pluralSeparator: undefined,
contextSeparator: undefined,
});
export default i18n;
This is how I use it :
import i18n from 'i18n';
export const defaultCountryByLanguage = () =>
i18n.language === 'en'
? { country: 'Germany', code: 'DE', prefix: '49', nationality: 'German' }
: { country: 'Deutschland', code: 'DE', prefix: '49', nationality: 'Deutsch' };
The ternary operator doesn't work because i18n.language
says it's null, yet when I print it shows the values.
Upvotes: 0
Views: 4779
Reputation: 644
please try to add initImmediate: false, to your config
Set it to false if your backend loads resources synchronously - that way.
for more details check the documents https://www.i18next.com/overview/configuration-options
your config should be like this
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import backend from 'i18next-http-backend';
i18n
.use(backend)
.use(initReactI18next)
.init({
lng: window.location.pathname.split('/')[1] !== 'en' ? 'de' : 'en',
fallbackLng: 'de',
whitelist: ['en', 'de'],
debug: process.env.NODE_ENV === 'development',
backend: {
loadPath:
process.env.NODE_ENV === 'development'
? '/locales/{{lng}}/{{ns}}.json'
: '/static/locales/{{lng}}/{{ns}}.json',
addPath:
process.env.NODE_ENV === 'development'
? '/locales/add/{{lng}}/{{ns}}.json'
: '/static/locales/add/{{lng}}/{{ns}}.json',
crossDomain: true,
},
ns: 'translations',
defaultNS: 'translations',
interpolation: {
escapeValue: false,
formatSeparator: undefined,
unescapePrefix: undefined,
nestingOptionsSeparator: undefined,
},
keySeparator: false,
nsSeparator: false,
pluralSeparator: undefined,
contextSeparator: undefined,
////add inside config
initImmediate: false,
});
export default i18n;
Upvotes: 1