Reputation: 2516
I'm trying to fetch value from Async Storage and assign it to State. Value of state is coming null/undefined while accessing inculcating to URL
constructor(props) {
super(props);
this.state = {
stAccntList: [],
stUserAccountNo: '',
stCustNo: '',
resp: '',
};
AsyncStorage.getItem('UserAccountNo').then((value) => {
if (value != '') {
accno = value;
this.setState({ stUserAccountNo: value });
// alert(this.state.stUserAccountNo);
}
}).done();
AsyncStorage.getItem('CustomerNo').then((value) => {
if (value != '') {
cusno = value;
this.setState({ stCustNo: value });
// alert(this.state.stUserAccountNo);
}
}).done();
}
componentWillMount() {
let restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;
}
this.state.CustNo and this.state.stUserAccountNo is returning null .
Please let me know where its going wrong.
Upvotes: 1
Views: 144
Reputation: 281894
Since you are trying to fetch data asynchronously and updating state, its not guranteed that the data is available before the componentWillMount is executed.
You could make use of async-await
in componentDidMount instead
constructor(props) {
super(props);
this.state = {
stAccntList: [],
stUserAccountNo: '',
stCustNo: '',
resp: '',
};
}
async componentDidMount() {
var userAccountNo = await AsyncStorage.getItem('UserAccountNo');
var CustomerNo = await AsyncStorage.getItem('CustomerNo');
if (userAccountNo != '') {
this.setState({ stUserAccountNo: userAccountNo });
}
if (CustomerNo != '') {
this.setState({ stCustNo: CustomerNo });
}
if(userAccountNo !== '' && CustomerNo !== '') {
var restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;
}
}
Upvotes: 2
Reputation: 1187
Is the restURL
used right away or at a later time (ie. click event or some other event later)? If it is used right away, you will likely want to use promises or async await to track when both AsyncStorage
have completed before using restURL. If you are using the URL at a later time, then you could simply rely on it completing before you need to use it or check right before use.
Upvotes: 0