Trying to set an app using Typescript React on expo that can show a different language based on a user selection, but doesn't seem to be working.I've made it store the selected language in asyncStorage
and called await AsyncStorage.getItem('language')
to get the language, my code is below. If console.log is run on asyncStorage, I was able to retrieve the value.
Interestingly, language works without any flaws when I use Localization.locale
, so wondering if it's being asyncStorage
is taking too long to get a result?
import I18n from 'i18n-js'import AsyncStorage from '@react-native-community/async-storage'import en from './en.json'import zh from './zh.json'I18n.translations = { en, zh}async function getLanguage() { try { const value = await AsyncStorage.getItem('language') if (value != null) { I18n.locale = value.slice(0,2) I18n.fallbacks = true } } catch(e) { console.log(e) }}getLanguage()export function t(name: string) { return I18n.t(name)}
Language selector (stores the selected language in asyncStorage)
import AsyncStorage from '@react-native-community/async-storage'import { Updates } from 'expo';export default function LanguageChange() {const onPress = async (language: string) => { await AsyncStorage.setItem('language', language); Updates.reload();} return (<View style={styles.languageContainer}><TouchableOpacity onPress={() => onPress("en")}><Text>English</Text></TouchableOpacity><TouchableOpacity onPress={() => onPress('zh-CN')}><Text>Chinese</Text></TouchableOpacity></View> );}
Edit 1
I've tried using .then
as well to see if there was a different result, but it's still the same.
AsyncStorage.getItem('language').then((result) => { I18n.locale = result.slice(0,2)})