Search code examples
javascriptreactjsinternationalizationlocal-storagelinguijs

ReactJS - How to create a fallback language function with localeStorage


I am having some trouble deciding on what to do with my language app. As you can see below I use "window.localStorage.setItem(LOCAL_STORAGE_KEY, locale);" to get the browser's locale. I have two languages es and en. But when someone has another language that is not es or en for example when it detects a language with locale inheritance ex: "es-ES"

(Passed here: (/imports/cuadds/both/locales/${locale}/messages)) I get errors such as:

Error: Cannot find module '/imports/cuadds/both/locales/es-ES/messages'

How can I create a function that makes the locale default to en or es when a language is not found?

import { i18n } from "@lingui/core";
import { detect, fromStorage, fromNavigator } from "@lingui/detect-locale";
import { en, es } from "make-plural/plurals";

let isActivated;

const startupI18n = () => {
    if (isActivated) return;
    isActivated = true;

    i18n.loadLocaleData({
        en: { plurals: en },
        es: { plurals: es },
    });

    dynamicActivate(getLocale());
};

export default startupI18n;

const LOCAL_STORAGE_KEY = "lang";

// defines where the locale falls back to (passed to dynamicActivate)
const DEFAULT_LOCALE = "es";

/**
 * Load messages for requested locale and activate it.
 */
export async function dynamicActivate(locale) {
    try {
        const module = await import(`/imports/cuadds/both/locales/${locale}/messages`);

        i18n.load(locale, module.messages);
        i18n.activate(locale);

        // saves the language to the localStorage
        window.localStorage.setItem(LOCAL_STORAGE_KEY, locale);
    } catch (error) {
        console.log(error);
    }
};

function getLocale() {
    const detectedLocale = detect(
        fromStorage("LOCAL_STORAGE_KEY"),
        fromNavigator(), 
        DEFAULT_LOCALE,
    );
    return detectedLocale;
}

Solution

  • I'm not familiar with the library you are using, but would this work?

    function getLocale() {
        const detectedLocale = detect(
            fromStorage("LOCAL_STORAGE_KEY"),
            fromNavigator(), 
            DEFAULT_LOCALE,
        );
    
        // if detectedLocale is 'en' or 'es' return
        if (['en', 'es'].indexOf(detectedLocale) >= 0) {
            return detectedLocale
        }
        // else return default value
        return DEFAULT_LOCALE;
    }