i18next-http-backend is making multiple API calls

2.3k Views Asked by At

I am applying internationalisation to my app with i18Next. The translation resources are severed via REST micro service. I am using i18next-http-backend plugin to fetch the translations.

The problem is that the plugin is making multiple API calls instead of one and I am not sure why enter image description here

This is how my code looks like

i18n
    .use(HttpApi)
    .use(initReactI18next) 
    .init({
        backend: {
            backends: [
                HttpApi,
                HttpApi,
                resourcesToBackend(localResources) // 2nd fallback
            ],
            backendOptions: [
                {
                    loadPath: HOST,
                    queryStringParams: {file: FILENAME, languageCode: `${langMap[lang]}`}, // primary API call
                    parse: (data) => parseTranslation(data),
                },
                {
                    loadPath: HOST,
                    queryStringParams: {file: FILENAME, languageCode: `${langMap['en']}`}, // 1st fallback
                    parse: (data) => parseTranslation(data),
                }
            ],

        },
        fallbackLng: 'en',
        lng: 'en', // TODO: make dynamic
        debug: true,
        keySeparator: false,
        interpolation: {
            escapeValue: false,
        },
    });

P.S HOST and FILENAME are variables here

2

There are 2 best solutions below

4
On
1
On
      const loadResources = async (locale: string) => {
    return await axios
      .get(`${BASE_URL}/lang/strings/${locale}/translation.json`, {
        headers: { "Access-Control-Allow-Origin": "*" },
      })
      .then((res) => {
        return JSON.stringify(res.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  const backendOptions = {
    loadPath: "{{lng}}|{{ns}}",
    request: (options: any, url: any, payload: any, callback: any) => {
      try {
        const [lng] = url.split("|");
        loadResources(lng).then((response) => {
          callback(null, {
            data: response,
            status: 200,
          });
        });
      } catch (e) {
        console.log(e, "error from language");
        callback(null, {
          status: 500,
        });
      }
    },
  };

  i18n
    .use(backend)
    .use(initReactI18next)
    .init({
      backend: backendOptions,

      fallbackLng: "en",
      debug: false,
      lng: "en",
      ns: ["translations"],
      defaultNS: "translations",
      interpolation: {
        escapeValue: false,
        formatSeparator: ",",
      },
    })
    .then(noop)
    .catch(noop);

I hope this would be helpful for you