0

Almost I tried every solution found on Stackoverflow that didn't work for me in any way.

I am trying to translate the REST API content after fetching its data.

Here are below some snippets:

i18n.js:

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

const loadResources = async (locale) => {
  return await axios
    .get("https://jsonplaceholder.typicode.com/posts", {
      params: { lang: locale },
    })
    .then((res) => {
      return res.data.slice(0, 3);
    })
    .catch((err) => {
      console.log(err);
    });
};

const detectorOptions = {
  order: ["cookie", "localStorage", "navigator"],

  lookupCookie: "locales",
  lookupLocalStorage: "locales",

  caches: ["localStorage", "cookie"],
  excludeCacheFor: ["cimode"],
  checkWhiteList: true,
};

const backendOptions = {
  loadPath: "/locales/{{lng}}/{{ns}}.json", //used to pass language and namespace to custom XHR function
  request: (options, url, payload, callback) => {
    try {
      const [lng] = url.split("|");

      loadResources(lng).then((data) => {
        callback(null, {
          data: JSON.stringify(data),
          status: 200, //status code is required by XHR plugin to determine success or failure
        });
      });
    } catch (e) {
      console.error(e);
      callback(null, {
        status: 500,
      });
    }
  },
};

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: "en",
    backend: {
      loadPath: "/locales/{{lng}}/{{ns}}",
    },
    detection: detectorOptions,
    whitelist: ["en", "zh", "jp", "fr"],
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

Demo.js

import { useTranslation } from "react-i18next";
import axios from "axios";
import { useEffect, useState } from "react";

export default function Demo() {
  const { t } = useTranslation();
  const [data, setData] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        setData(res.data.slice(0, 3));
      })
      .catch((err) => {
        console.log(err);
      });
}, [data]);


return (
    <>
    <section>
        {data.map((i, index) => {
          return (
            <>
              <div key={index}>
                <h4>{i.title}</h4>
                <p>{i.body}</p>
              </div>
            </>
          );
        })}
      </section>
   </>
)

I don't know how can I load the translations from REST API content using Axios. But I know that i18next-http-backend is used for loading the translations.

To be noted: I found these 3 links that don't help me.

locales are located in my public folder public\locales\{lng}.json

Also, This github issue I found where link is broken :(

i18next-http-backend github issue

since yesterday I couldn't find any way to solve this issue. Also, it's confusing me a lot!

Please help me!

1 Answer 1

0
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useTranslation } from 'react-i18next';

const YourComponent = () => {
  const { t } = useTranslation();
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('YOUR_API_ENDPOINT');
        // Assuming your API response has a field 'content' to be translated
        const translatedData = {
          ...response.data,
          content: t(response.data.content),
        };
        setData(translatedData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [t]);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <p>{data.content}</p>
      {/* Render other translated content */}
    </div>
  );
};

// LanguageSwitcher.jsx

import React from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSwitcher = () => {
  const { i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('fr')}>French</button>
      {/* Add more language buttons as needed */}
    </div>
  );
};

export default LanguageSwitcher;
Sign up to request clarification or add additional context in comments.

3 Comments

Im getting this error: TypeError: key.indexOf is not a function
do I have to cutomize something in i18n.js?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.