Reputation: 3971
I have this async code function to get lang var from AsyncStorage. And I want to call this function on every app page in construct(?) method. But when I try to call it, it looks like the code run synchronous, and my loadedLang is = { _45: 0, _81: 0, _65: null, _54: null }. How to do it in right way? Thanks.
main.js
import load from "./components/languageLoad"
constructor(props) {
super(props);
let loadedLang = load();
console.log("LOADED", loadedLang);
this.state = {
settings: 1,
deviceLocale: "EMPTY"
};
}
languageLoad.js
import React, { Component } from 'react';
import { AsyncStorage} from 'react-native';
import Lang from 'react-native-i18n'
export default load = async () => {
try {
const customLang = await AsyncStorage.getItem('customLang');
if (customLang !== null && customLang !== undefined && customLang !== "") {
deviceLocale = customLang;
}
} catch (error) {
deviceLocale = Lang.locale.split("-")[0] || "uk";
}
console.log("------------", deviceLocale, '-------------');
console.log("------------", Lang.t('aboutAppText') , '-------------');
Lang.locale = deviceLocale;
return Lang;
}
Upvotes: 2
Views: 10376
Reputation: 53931
async
functions need to be called with await
and can only be called from inside of async functions.
JS constructors can't be asynchronous. Therefore you will have restructure your code to work differently. Either load the data outside of a constructor, or have an anonymous self executing async function in the constructor that will load the data and store it. Of course the rest of the class will need to work with the fact that the data might not be there.
Upvotes: 5