It is impossible to not reset preferences without storage

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the apps category.

Last Updated: 2021-05-16

I was in charge of localization of a React Native app. I had this code in translation.js:

export function switchLocale(locale = "de") {
  i18n.locale = locale;
  i18n.fallbacks = true;
}

// Purpose: Switch to the correct locale when booting app
switchLocale(autoDetectedLocale);

This worked on my "single use" tries: it would be English (auto-detected first) due to top-level execution of switchLocale. The language would be able to switch to German too during app usage if the user pressed the button in the app for this.

But had a bug: if you turned off the app and went back in, the user's locale was not remembered.

I considered grabbing the user's preferred language via the API, but this too would not work, since the user would not be logged in yet therefore we don't know their preferences and don't know what language to show their login form in.

I should have stored this preference in persistent storage on the device.

export function switchLocale(locale = "de") {
  // We need to persist the preferences across sessions.
  SecureStore.setItemAsync("locale", locale);
  i18n.locale = locale;
  i18n.fallbacks = true;
}

SecureStore.getItemAsync("locale").then((value) => {
  if (value) {

    log("Found locale setting in persistent storage", value);
    switchLocale(value);

  } else {

    log("Did not find any locale in persistent storage");
    const autoDetectedLocale = Localization.locale;
    switchLocale(autoDetectedLocale);

  }
});