Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i18next.services.pluralResolver.addRule returns undefined for addRule

Tags:

i18next

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

const locales = ['en-GB', 'pl-PL'];
export const supportedLanguages = locales;

const localeResources = {
  'en-GB': {
    common: require('./locales/en-GB/common.json'),
  },
  'pl-PL': {
    common: require('./locales/pl-PL/common.json'),
  },
};

const frozenLocales = Object.freeze(locales);
export function localesImmutable() {
  return frozenLocales;
}

const fallbackLanguages = {
  pl: ['pl-PL'],
  default: ['en-GB'],
};

i18next.services.pluralResolver.addRule('pl', {
  numbers: [1, 2, 3],
  plurals: function (n) {
    return Number(
      n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
    );
  },
});

const i18n = i18next;
i18n.use(LanguageDetector).init({
  resources: localeResources,
  fallbackLng: fallbackLanguages,
  ns: 'common',
  defaultNS: 'common',
  react: { wait: true },
  debug: false,
  cache: { enabled: true },
});

export default i18n;

I followed this link to override plural rule for my project. When I try to override the plural rule, I can't. pluralResolver doesn't seem to have addRule method. I get TypeError: Cannot read property 'addRule' of undefined. What am I missing? The translation is for Polish plurals.

like image 368
Ömer Keskinkilic Avatar asked Oct 30 '25 01:10

Ömer Keskinkilic


1 Answers

You should call addRule only after the init is done.

i18n
  .use(LanguageDetector)
  .init({
    resources: localeResources,
    fallbackLng: fallbackLanguages,
    ns: 'common',
    defaultNS: 'common',
    react: { wait: true },
    debug: false,
    cache: { enabled: true },
  })
  .then(() => {
    // this called after the init finished
    i18n.services.pluralResolver.addRule('pl', {
      numbers: [1, 2, 3],
      plurals: function (n) {
        return Number(
          n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
        );
      },
    });
  });
like image 53
felixmosh Avatar answered Nov 02 '25 22:11

felixmosh