Blog>
Snippets

Custom Configuration Strategies for Internationalization with TanStack Config

Illustrate a custom solution for managing internationalization settings in a multi-language web application, using TanStack Config to store and apply language preferences dynamically.
import { createConfig } from 'tanstack-config';

// Define config structure
const config = createConfig({
  defaultConfig: {
    language: 'en'
  }
});
This code initializes TanStack Config with a default language setting. It imports the `createConfig` function from 'tanstack-config' library and sets up a basic configuration structure for an application, specifying 'en' (English) as the default language.
function setLanguage(language) {
  config.setConfig(current => ({
    ...current,
    language
  }));
}
Defines a `setLanguage` function that updates the current configuration with a new language. It uses the `setConfig` method from TanStack Config, which allows for the modification of the current configuration by taking a callback function. The callback receives the current configuration, spreads it, and updates the `language` property with a new value.
function applyLanguage() {
  const userLang = navigator.language || config.getConfig().language;
  setLanguage(userLang);
  document.documentElement.lang = userLang;
}
This function, `applyLanguage`, detects the user's preferred language using `navigator.language`, or falls back to the default language defined in TanStack Config's configuration. It then updates both the configuration and the `lang` attribute of the document, ensuring that the entire document is marked for the correct language context.