Reputation: 2835
How to get AsyncStorage item at "componentDidMount", here my code
componentDidMount() {
AsyncStorage.getItem('customer_id').then((value)=> this.setState({ customer_id: value }));
console.log(this.state.customer_id); /* doesn't work */
console.log(`${this.state.customer_id}`); /* doesn't work */
}
render() {return <View><Text>Customer ID : {this.state.customer_id}</Text></View>; /* it's work */ }
Upvotes: 2
Views: 2185
Reputation: 2835
here my answer, with modification from Ryan answers
var cust_id_tmp = '';
AsyncStorage.getItem('customer_id', function(errs, result) {
if (!errs) {
if (result !== null) {
//this.setState({customer_id:result}); <= we can't do this
cust_id_tmp = result;
console.log('customer_id : ' + result); /* it works */
}
}
}).then((value) => this.setState({
cust_id: cust_id_tmp
}));
Upvotes: 0
Reputation: 3934
You have to handle AsyncStorage
- asynchronously, funny that! Anyway, you want to pass in a callback to the getItem
method that handles the results. Try
componentDidMount(){
AsyncStorage.getItem('customer_id', (error,value) => {
if (!error) { //If there are no errors
//handle result
if (result !== null) this.setState({customer_id:value});
}
});
}
Upvotes: 3
Reputation: 780
try {
const value = await AsyncStorage.getItem('@MySuperStore:key');
if (value !== null){
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
For more information you can visit official docs.
Upvotes: 1