Utilizing Async Storage for Language Localization

Currently, I am utilizing two separate APIs for localization, both of which return JSON data.

getEnLoc() //400kb
getEsLoc() //400kb

My plan is to call these APIs in App.ts during the app's initialization phase and store the retrieved JSON objects in async storage. Subsequently, when any page needs to be translated, the key-value pairs in the local storage will be consulted.

// In App.ts
AsyncStorage.setItem('@storage_Key', getEnLoc())
// In Home.tsx
const jsonValue = await AsyncStorage.getItem('@storage_Key')

What are your thoughts on this approach? Do you foresee any potential performance issues arising from this logic?

Answer №1

If you want to implement localization in your app, consider using the language key in AsyncStorage such as 'en', 'en_US', or 'tr_TR'. Create separate language JSON files like en.json for each language. This class structure can be used for localization:

import { NativeModules, Platform } from 'react-native';
import { strings } from 'res';

class LanguageHelper {
  currentLanguage = null;
  currentStrings = null;

  init() {
    this.currentLanguage = this.determineDeviceLanguage();
    this.setCurrentString();
  }

  setCurrentString() {
    switch (this.currentLanguage) {
      case 'tr_TR':
        this.currentStrings = require("./tr.json");
        break;
      default:
        this.currentStrings = require("en.json");
    }
  }

  determineDeviceLanguage() {
    // Determine device language
    const language =
      Platform.OS === 'ios'
        ? NativeModules.SettingsManager.settings.AppleLocale ||
          NativeModules.SettingsManager.settings.AppleLanguages[0]
        : NativeModules.I18nManager.localeIdentifier;

    return language;
  }
}

const LanguageProvider = new LanguageHelper();

export default LanguageProvider;

The en.json file should look like this:

{
    "title": "Hello World"
}

In your App.js file, import the LanguageProvider class:

import LanguageProvider from './LanguageHelper';

const App = () => {
    useEffect(() => {
    LanguageProvider.init(); // Init language
}, []);
    return(/* Your components */)
}

Then you can access localized strings anywhere in your app after importing:

LanguageProvider.currentStrings.title

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

Implementing a click function that toggles between adding and removing a class, keeping track of the number of clicks, and utilizing localStorage to prevent repeated clicking in the

Hi there! I'm currently working on a simple widget that features a clickable icon and a counter next to it. When the icon is clicked, it should toggle between an empty heart and a filled heart using addClass/removeClass. Additionally, each click incr ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

A guide on creating a function that can detect if an object is not iterable and then throw an error

Exploration Uncomfortable type definition at the library: declare type Extension = { extension: Extension; } | readonly Extension[]; Type-validation function export function isIterable(x: any): x is Iterable<unknown> { return Symbol.iterator ...

Using useState as props in typescript

Let's imagine a situation where I have a main component with two smaller components: const MainComponent = () => { const [myValue, setMyValue] = useState(false) return ( <> <ChildComponent1 value={myValue} setValue={set ...

Modify the empty message for the PrimeNG multiselect component

Is there a way to customize the message 'no results found' in p-multiselect on Angular? I have successfully changed the default label, but I am struggling to find a solution to override the empty message. Here is my code snippet: <p-multiSel ...

What is the process of importing an IIFE-based JavaScript module into an Angular TypeScript application?

I have come across a third-party SDK that is structured as an oldschool IIFE based module. The code looks something like this: var ThirdPartySDK = (function() { var export = {}; // Adding some methods to export return export; })(); To use this SD ...

Best practices for receiving messages from SQS in Node.js

I am exploring how to implement SQS in a similar manner as RabbitMQ or Kafka, where we usually set up a listener. However, after going through their documentation, I couldn't find any instructions on how to set up a listener for SQS: Currently, I am ...

Having trouble getting the styles property to work in the component metadata in Angular 2?

Exploring Angular 2 and working on a demo app where I'm trying to apply the styles property within the component metadata to customize all labels in contact.component.html. I attempted to implement styles: ['label { font-weight: bold;color:red } ...

Encountering a ReactJs and TypeScript error: "menuItems.map is not a function, issue with map method"

Greetings! I am currently working on implementing the logic of using useState and mapping an array to show only one dropdown item at a time. Below is my array structure with tags (menu name, links (to router), icon (menu icon), and if there are dropdown i ...

I'm looking for the configuration of function definitions for the Jasmine npm module within an Angular project. Can

When a new Angular project is created, the *.spec.ts files provide access to Jasmine functions such as "describe", "beforeEach", and expect. Despite not having an import clause for them in spec.ts files, I can click on these functions and navigate to their ...

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...

Utilizing TypeScript 2's Absolute Module Paths

The issue at hand: I am facing a challenge with relative module paths and have attempted to resolve it by configuring the baseUrl setting in my tsconfig.json file. Despite my efforts, I keep receiving an error indicating that the module cannot be found. I ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...

Encountering a problem during the creation of a react native application

After successfully installing Nodejs, Java, Python, and Android Studio, I proceeded to install create-react-native-app using the following command: npm install -g create-react-native-app However, when trying to run the command sudo create-react-native-ap ...

Can someone explain the meaning of this syntax in a TypeScript interface?

Just the other day, I was trying to incorporate the observer pattern into my Angular 4 application and came across this TypeScript code snippet. Unfortunately, I'm not quite sure what it means. Here's the code: module Patterns.Interfaces { ...