I have a part of code that loads the stored language of i18n. I am trying to get the language, change the state to true and then show the page on screen.
The code doesn't update the "yesLanguage" state and it still return false..
The code must return TRUE "yesLanguage".
The goal of the code is to set default language of application before showing the screen then showing the screen with a default language (language the the user recently set).
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
/*
import React from 'react';
import {Text} from 'react-native';
//import {SignUpScreen} from './src/components/PlayAround/ResponsiveLayout';
import {HomeScreen} from './src/screens/HomeScreen';
function App (props){
return(
<HomeScreen />
);
}
export default App;
*/
import React,{useState,useEffect} from 'react';
import './translations/i18n';
import {View, Text,Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {HomeScreen} from './src/screens/HomeScreen';
import 'intl-pluralrules';
function App(props){
const {t, i18n} = useTranslation();
const [currentLanguage,setLanguage] = useState('ar');
const [yesLanguage , setYesLanguage] = useState(false);
const changeLanguage = value => {
i18n
.changeLanguage(value)
.then(() => setLanguage(value))
.catch(err => console.log(err));
AsyncStorage.setItem('currentLnaguage',value);
};
React.useEffect(()=>{
AsyncStorage.getItem('currentLnaguage').then(val => {
//console.log(val+'useeee2');
let newDefaultLang = val ? val :"ar"; // or Change ar with the default language
i18n.locale = newDefaultLang;
changeLanguage(newDefaultLang);
//
setYesLanguage(true);
console.log(newDefaultLang+"qqqq");
});
},[]);
console.log(yesLanguage);
//AsyncStorage.clear();
return yesLanguage && <HomeScreen buttonTitle={t('ordernow')} deliveryText={t('delivery')} />
};
export default App;
update here is my i18n file code
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
//import LanguageDetector from 'i18next-browser-languagedetector';
import en from './en/en.json';
import ar from './ar/ar.json';
import he from './he/he.json';
import AsyncStorage from '@react-native-async-storage/async-storage';
import React from 'react';
/*
i18n
.use(initReactI18next).init({
lng: 'en',
fallbackLng: 'en',
resources: {
en: en,
ar: ar,
},
interpolation: {
escapeValue: false // react already safes from xss
}
});*/
const getDefaultLang = async () => {
const storedLang = await AsyncStorage.getItem('currentLnaguage');
/*if(storedLang!= null){
i18n.defaultLocale = storedLang;
i18n.locale = storedLang;
i18n.fallbacks = true;
}*/
return i18n
.use(initReactI18next)
.init({
resources: {
en: en,
ar: ar,
he: he
},
lng: storedLang ? storedLang : 'ar',
//lng: storedLang || "ar",
interpolation: {
escapeValue: false,
},
fallbackLng: ['en', 'ar','he'],
});
};
export default getDefaultLang();