i18next / i18next-xhr-backend

[deprecated] can be replaced with i18next-http-backend
https://github.com/i18next/i18next-http-backend
MIT License
253 stars 75 forks source link

Language lookup logic result in errors in i18next.changeLanguage #280

Closed dyniper closed 5 years ago

dyniper commented 6 years ago

When using i18next in combination with i18next-xhr-backend, the language lookup sequence leads to errors in the changeLanguage callback.

Given this init:

 i18next
    .use(i18nextXHR)
    .init({
      lng: "en",
      fallbackLng: "en",
      debug: false,
      backend: {
        loadPath: url + "/tests/{{lng}}.json",
        crossDomain: true,
        parse: (data: string) => JSON.parse(stripJsonComments(data))
      }
    }, (err, t) => {
      // done
    });
  });

and changeLanguage:

i18next.changeLanguage("fr-CA",
      (err, t) => {
        if (err) {
          console.error("changeLanguage", err);
        }
        // done
      }
    );

If my string resource is simply fr-CA.json, the callback in changeLanguage will receive an error (failed loading .../tests/fr.json).

This makes it impossible to know if the resource could not be found at all, or if it was found using some fallback lookup. In the example i gave, i don't even understand why it's even trying to load fr.json, as the requested language is fr-CA.

But the same problem happens if i have en.json resource and request language for en-UK. It will work (by loading en.json), but still have an error in the changeLanguage callback. Wouldn't it only make sense to have errors if the resource could not be loaded at all?

Thanks!

jamuhl commented 6 years ago

read the documentation: https://www.i18next.com/principles/fallback#language-fallback

resolve order is: en-US -> en -> fallbackLng

so fr-CA will also try to load fr (by default it assumes you only translated the things spelled different from fr in fr-CA not all the strings).

you can play with: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources the load option

dyniper commented 6 years ago

Sorry if I didn't explain correctly. It is fine that it's trying to load fr.json according to the fallback logic. What I find odd, is that the callback to changeLanguage receive errors of it. Because of it, there is no way to distinguish a real failure (no language files found at all of the a given locale), and failing getting a fallback language.

jamuhl commented 6 years ago

i guess loading fallbackLng will work always - so every not loaded is an error - work with whitelist option to avoid loading non supported languages.