0

I have below code for translation in react app.

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import HttpApi from "i18next-http-backend";

    i18n
      .use(initReactI18next)
      .use(HttpApi)
      .init({
        lng: "en",
        fallbackLng: "en",
        keySeparator: false,
    
        interpolation: {
          escapeValue: false,
          /**
           * Add interpolation format method to customize the formatting
           */
          format: (value, format, lng) => {
            if (format === "uppercase") {
              return value.toUpperCase();
            }
    
            return value;
          }
        },
        backend: {
          loadPath: "/locales/{{ns}}/{{lng}}.json"
        }
      });

Here in the above code data is saved in static file in locale folder. I need to read the data from backend API instead from files. I mean in below code instead of loadPath I need to call API. is it possible in react?

        backend:{
          loadPath: "/locales/{{ns}}/{{lng}}.json"
        }
Shruti sharma
  • 199
  • 6
  • 21
  • 67

2 Answers2

0

This answer may help: how to incorporate API data in i18next instead of static file

i18next-http-backend is also able to accept an injected request function: https://github.com/i18next/i18next-http-backend#backend-options enter image description here

adrai
  • 2,495
  • 1
  • 15
  • 18
0

Below code is working for me.

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import backend from 'i18next-http-backend';
import api from "../api";


 alert(navigator.language); 
 var lang=navigator.language;
 if(lang==='en-US')
  lang='en';
let loadResources= api.getTranslations(lang);
const backendOptions = {
  loadPath: 'http://localhost:8080/country/'+lang, 
  request: (options, url, payload, callback) => {
    try {
      loadResources.then((result) => {
        callback(null, {
          data: result,
          status: 200, 
        });
      });
    } catch (e) {
      console.error(e);
      callback(null, {
        status: 500,
      });
    }
  },
};

i18n
  .use(LanguageDetector)
  .use(backend)
  .init({
    backend: backendOptions,
    fallbackLng: "fr",
    debug: false,
    load:"languageOnly",
    ns: ["translations"],
    defaultNS: "translations",
    keySeparator: false, 
    interpolation: {
      escapeValue: false, 
      formatSeparator: ","
    },
    react: {
      wait: true
    }
});
i18n.changeLanguage(navigator.language);
export default i18n;
Shruti sharma
  • 199
  • 6
  • 21
  • 67
  • hi shruti , can you please explain me why is the load path , 'http://localhost:8080/country/'+lang , i am trying to implement the similar thing , but just confused what would loadpath be . – Sarthak Gupta Jan 18 '23 at 05:26