i18next / i18next-localstorage-backend

This is a i18next cache layer to be used in the browser. It will load and cache resources from localStorage and can be used in combination with the chained backend.
MIT License
88 stars 43 forks source link

Get the REST API data translations stored in localstorage #50

Closed Namnika closed 10 months ago

Namnika commented 10 months ago

🐛 Bug Report

Hi all, I'm facing problem related to this same issue #48 , but I have set my locales to my public dir, so there is no in-memory translation resources. I read all docs and closed issues even i18next-localstorage-backend and halfway I am stuck on how to get the translations in localStorage.

I'm using react-i18next, i18next-browser-languagedetector, i18next-http-backend, i18next-localstorage-backend and i18next-chained-backend.

So here is my process:

To Reproduce

my i18n.js config file:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import HttpBackend from "i18next-http-backend";
import LocalStorageBackend from "i18next-localstorage-backend";
import ChainedBackend from "i18next-chained-backend";

const detectorOptions = {
  order: ["cookie", "localStorage", "navigator"],
  lookupCookie: "locales",
  lookupLocalStorage: "locales",
  caches: ["localStorage", "cookie"],
  checkWhiteList: true,
};

i18n
  .use(ChainedBackend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: "en",
    ns: "translation",
    load: "languageOnly",  
    detection: detectorOptions,
    whitelist: ["en", "zh", "jp", "fr"],
    interpolation: {
      escapeValue: false,
    },
    backend: {
      backends: [LocalStorageBackend, HttpBackend],
      backendOptions: [
        {
          prefix: "i18next_res_",
          expirationTime: 7 * 24 * 60 * 60 * 1000, //for 7 days
        },

        {
          loadPath: "/locales/{{lng}}/translation.json",
        },
      ],
    },
    react: {
      useSuspense: false,
    },
  });

export default i18n;

translation.json:

{
  "data": [
    {
      "title": "{{title}}",
      "body": "{{body}}"
    }
  ]
}

I saw this

//
"arrayJoinWithInterpolation": [
        "you",
        "can",
        "{{myVar}}"
      ],

i18next.t('arrayJoinWithInterpolation', { myVar: 'interpolate'});

from Objects and Arrays and tried like this interpolation {{myvar}} but doesn't work for me.

Demo.js:

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

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

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

This what I'm getting some changes in my localStorage:

Screenshot (413)

Screenshot (415)

Screenshot (416)

Also, have one more question, Is it okay to use both load and whitelist or one of them? Can you give some suggestions on this issue?

Expected behavior

I am expecting to get translations in localstorage.

Your Environment

adrai commented 10 months ago

regarding the array, you need to pass the joinArrays option:

i18next.t('arrayJoinWithInterpolation', { myVar: 'interpolate', joinArrays: ' ' });

Regarding the load and whitelist option:

The whitelist option does not exist anymore, use supportedLngs: https://www.i18next.com/misc/migration-guide#removed-deprecated And yes, you can have load and supportedLngs

Namnika commented 10 months ago

Hi @adrai Thanks for your quick response! Yes, I used supportedLngs.

But I'm still getting this title like this not the translation even in localStorage too!

Screenshot (417)

sample : I did like this

<h4>{t("title", { title: "interpolate", joinArrays: " " })}</h4>

What I'm doing wrong? Thank you.

adrai commented 10 months ago

I don't understand exactly what you're trying to do, and where your translations should get from, but here you have an example: https://codesandbox.io/p/sandbox/cocky-hertz-vhm6sd

I think your issue is not related to the localstorage-backend or the http-backend at all

adrai commented 10 months ago

If you just show the data you receive (title, body, etc...), why do you need i18next for that? Simply display your data. i18next will not magically translate that data for you.

Namnika commented 10 months ago

Thankyou. but sorry for misunderstanding, now I got the point like dynamically i18next can't translate the data. yes, I actually did to simply show the data.

but I am wondering will open ai can give something like dynamic translation or any other lib?

can you pls suggest actually I want to give the translated data to user when they change the language option to get in multiple languages.

adrai commented 10 months ago

Normally, you have 3 options: Option 1) integrate an external service and translate on-the-fly (like google translate api etc...) Option 2) use a CMS and have your data there and translate it there or have your data translated already in your server side (or wherever the data is coming from) Option 3) move all your data out to an external TMS (like locize) and integrate that one with i18next to directly receive the translated content. (you still need to translate that content somehow in locize, with machine translations or manually, etc...)