Pressing the F5 key will cause i18next to revert back to the original default

i18n.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import enTranslation from '../locales/en.json';
import trTranslation from '../locales/tr.json';
import deTranslation from '../locales/de.json';
import I18nextBrowserLanguageDetector from 'i18next-browser-languagedetector';
const resources = {
    en: {
        translation:
            enTranslation
    },
    tr: {
        translation:
            trTranslation
    },
    de: {
        translation:
            deTranslation
    },

};


i18n.use(initReactI18next).init({
    resources,
    debug: true,
    fallbackLng: 'de',
    interpolation: {
        escapeValue: false,
    },

}).catch(e => console.log(e))

export default i18n;

_app.tsx

export default function App({ Component, pageProps }: AppProps) {
  
  return <>
    <Provider store={store}>
      <I18nextProvider i18n={i18n}>
        <Header />
        <Component {...pageProps} />
        <Footer />
      </I18nextProvider>
      <Script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedcd1d1cacdcaccdfcefe8b908f908d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></Script>
    </Provider>
  </>
}

LanguageSelect.tsx -Component in my header

import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSelection = () => {
    const { i18n } = useTranslation();

    const handleLanguageChange = (event: any) => {
        const selectedLanguage = event.target.value;
        i18n.changeLanguage(selectedLanguage);
    };

    return (

        <div style={{ zIndex: 99 }}>
            <select className='text-sm' defaultValue={i18n.language} id="language" onChange={handleLanguageChange}>
                <option value="en">EN</option>
                <option value="tr">TR</option>
                <option value="de">DE</option>
            </select>
        </div>
    );
};

export default LanguageSelection;

After starting the project, it defaults to DE language. When I switch it to TR or EN, it works fine until I refresh the page. Upon refreshing, it reverts back to DE. I am trying to maintain the last language selection but haven't been successful.

I have attempted various solutions found online, without success:

  • Tried removing fallbackLng - received hydrogen errors.
  • Tried fallbackLng: localStorage.getItem('i18nextLng') || 'de' - resulted in a "localStorage is not defined" error.
  • Tried lng:'de'.
  • Tried setting the language detector but couldn't get it to work either.

My goal is to retain the user's last language selection, perhaps based on their browser language preference (which would be ideal).

Answer №1

Manual execution is recommended.

Here's an example:

  • When the language is switched - store the language in Local Storage
  • Upon loading the app - retrieve the language from Local Storage and apply it to i18n

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

Customized Generic Types in TypeScript based on optional property conditions

In my React/Typescript app, I currently have the following code snippet - export type GetPricingParams = { search_id: number, promo_code?: string, }; export type GetPricingData = { amount: number, currency: string, search_id: number, ...

There is no valid injection token found for the parameter 'functions' in the class 'TodosComponent'

While working in my code, I decided to use 'firebase' instead of '@angular/fire'. However, I encountered an issue that displayed the following error message: No suitable injection token for parameter 'functions' of class &apos ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Why is it that my TypeScript isn't permitting the definition of Tuple Types?

When attempting to define a tuple type in my code, an error is being thrown. Is there a specific configuration within my Node.js application that needs to be adjusted in order to accept tuple types? ...

Revamp the button's visual presentation when it is in an active state

Currently, I'm facing a challenge with altering the visual appearance of a button. Specifically, I want to make it resemble an arrow protruding from it, indicating that it is the active button. The button in question is enclosed within a card componen ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

What could be causing TypeScript to raise an issue when a /// reference comes after the 'use strict' statement?

This particular inquiry is somewhat connected to a question I posted on Stack Overflow yesterday about why TypeScript is encountering issues when trying to import a module. The initial configuration remains unchanged. My TypeScript file appears as follows ...

Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples. function (times: Array<number> | Array<[number, number]>) { if (Array.isArray(times[0]) ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Access information from an http URL using AngularJS

Attempting to create an Angular application that showcases all of Google's public repositories on GitHub (https://github.com/google). I've successfully displayed a portion of it using the angular-in-memory-web-api: export class InMemoryDataServic ...

Signature in TypeScript for a function that augments the number of elements in a tuple

Can a type-aware declaration be written in Typescript for a function that takes a tuple and returns a new one with an appended item, without using function overload? In short, I need a function that performs the following: [T1, T2, ... Tn] + U => [T1 ...

An issue has been detected in the jsoneditor component of the ang-jsoneditor module at line 13, character 9

Currently, I am facing an issue with my angular project when running npm start. Strangely enough, the problem only arises after doing a fresh npm install, not when copying over the older node-modules folder. There haven't been any recent changes to my ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Angular 6 - Using properties in classes

Considering a component structured as follows: import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: '...', templateUrl: './...html', styleUrls: ['./...scss'] }) export class Te ...

What is the best way to instruct TypeScript to utilize a globally installed NPM @types package?

After running npm install @types/node, the TypeScript compiler worked perfectly with tsc -p tsconfig.json. However, when I attempted to install the package globally with npm install -g @types/node and deleted the local folder, I encountered the following ...

"Utilizing Primeng's dynamic functionality to create a selected p-tab

Utilizing the TabView module from primeng, I have created a dynamic tab where only the last tab remains static. The property used is 'selected', and for the dynamic tab, it is set as [selected]="'tab' + $index", where $index represents ...

Preventing data binding for a specific variable in Angular 2: Tips and tricks

How can I prevent data binding for a specific variable? Here's my current approach: // In my case, data is mostly an object. // I would prefer a global solution function(data) { d = data; // This variable changes based on user input oldD = da ...

When employing the pipe function within *ngFor, the webpage's refresh may vary, causing occasional updates

Utilizing angular2-meteor, I have already implemented pure: false. However, the pipe seems to be running inconsistently. For more details on the issue, please refer to my comments within the code. Thank you. <div *ngFor="#user of (users|orderByStatus) ...

Embark on your project with Adonisjs, utilizing both http and https protocols

Currently, I am seeking to have both HTTP and HTTPS operational in my adonisjs project. At the moment, my server.ts file is configured for HTTPS as shown below: import 'reflect-metadata' import sourceMapSupport from 'source-map-support' ...

The array is filled with values, however, there seems to be an issue preventing their access. What could possibly be causing this obstacle

After receiving two string values through a callback function, let's call them a and b, I attempt to store them in an array. However, when I check the array using console.log, it only displays the values if I expand the array by clicking on the arrow ...