Spook
Spook

Reputation: 25927

How to resolve "You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done"?

I'm using i18next to localize my React frontend application. The usage is as following:

import i18n from "i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
import { EnvData } from "../env/EnvData"

i18n
    // Add HTTP backend as a plugin
    .use(HttpApi)
    // Add React bindings as plugin
    .use(LanguageDetector)
    .use(initReactI18next)
    // Initialize the i18next instance
    .init({
        // Config options
        supportedLngs: ['pl', 'en'],

        // Fallback locale when translation is
        // missing
        fallbackLng: "en",

        // Debugging
        debug: EnvData.DEBUG,

        // Disable escaping code in translation text, because
        // React already does that
        interpolation: {
            escapeValue: false
        },

        detection: {
            // order and from where user language should be detected
            order: ['localStorage'],

            // keys or params to lookup language from
            lookupLocalStorage: 'LANGUAGE',

            // cache user language on
            caches: ['localStorage']
        },
        parseMissingKeyHandler: function(key) {
            return "#" + key;
        }
    });

i18n.loadNamespaces([
    // snip
]);

export default i18n;

In the App.tsx I'm initializing i18n in the following way:

import i18n from './i18n/config.ts';

// (...)

ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
        <I18nextProvider i18n={i18n}>

// (...)

However very often after starting the application I'm getting the error:

i18next: hasLoadedNamespace: i18next was not initialized (2) ['pl', 'en']

i18next::translator: key "error" for languages "pl, en" won't get resolved as namespace "common" was not yet loaded This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!

The problem is however that i18n initialization takes place in the root of my application and I fail to see how could I wrap the initialization in call().then() or await call().

Moreover majority of tutorials about i18n shows initializing it exactly the same way I'm doing it.

How can I solve this error?

Upvotes: 0

Views: 46

Answers (0)

Related Questions