Reputation: 39
I am a react-native newbie.
I'm trying to use Async Storage in my application. I want the async storage to store token when user log in, it will navigate to homescreen. At homescreen, im trying to get the token through async storage and print it on console but all i get is promise. I just want to know what is the proper way to use Async storage especially in storing token? I know the alternative for this problem is using Redux state management, but I'm trying to learn the basic method.
I've tried to store the token in a variable in ComponentWillMount(), but it still does not work.
class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
token = getToken();
}
render() {
const { navigate } = this.props.navigation;
console.log(token);
return (
<View style={styles.container}>
<Text> HomeScreen </Text>
</View>
);
}
}
const getToken = async () => {
let token = "";
try {
token = await AsyncStorage.getItem("token");
} catch (error) {
console.log(error);
}
return token;
};
Upvotes: 0
Views: 611
Reputation: 189
You should use it something like this,
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native';
//for storing Data
setName = (value) => {
AsyncStorage.setItem('name', value);
this.setState({ 'name': value });
}
//for Retrieving Data
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))
Here it is another simple example.
Upvotes: 0
Reputation: 1600
Try to use it with Async and await
setValue: function (key, value) {
AsyncStorage.setItem(key, value)
},
getValue: async (key) => {
let value = '';
try {
value = await AsyncStorage.getItem(key) || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return value;
}
Upvotes: 0
Reputation: 3118
First, I should note that componentWillMount
is deprecated and you can use constructor
or componentDidMount
instead.
if you log token in getToken
and after getting it, it will work fine. if you want to check if the user is logged in, you can do like this
constructor(props) {
super(props);
this.state = {};
getToken().then((token)=>{
console.log(token)
//check if user is logged in
})
}
or you can do this in componentDidMount
.
I hope this can help you
Upvotes: 4