i18next backend loadPath fails to map the data

3.1k Views Asked by At

i'm trying to load the translation from the third party using i18next, react-i18next and axios. Here is mine i18n.js:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { DateTime } from "luxon";
import Backend from "i18next-http-backend";
import axios from "axios";

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: "en",
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
      format: (value, format, lng) => {
        if (value instanceof Date) {
          return DateTime.fromJSDate(value)
            .setLocale(lng)
            .toLocaleString(DateTime[format]);
        }
        return value;
      },
    },
    backend: {
      loadPath: (lng) => {
        axios.get(`http://localhost:5000/${lng}`).then((res) => {
          console.log(JSON.stringify(res.data));
          return JSON.stringify(res.data);
        });
      },
    },
  });

export default i18n;

I can see on console that data is coming, but useTranslation() doesn't work anyway. Any idea why it's happening?

1

There are 1 best solutions below

2
On BEST ANSWER

The loadPath function is just there to get the path to load, not the actual load request.

enter image description here

To do so use the request option: enter image description here

https://github.com/i18next/i18next-http-backend#backend-options

Try something like this:

// ...
loadPath: `http://localhost:5000/{{lng}}',
request: function (options, url, payload, callback) {
  axios.get(url).then((res) => {
      callback(null, { status: 200, data: res.data });
  }).catch((err) => callback(err));
},
// ...

Here you can also find a dedicated test for the request option: https://github.com/i18next/i18next-http-backend/blob/master/test/http.spec.js#L178