I am Trying to get the username from AsyncStorage (React-Native). And parse this data in to a <Text></Text>
.
My current code displays nothing.
getCreds = () => {
return AsyncStorage.getItem('username')
}
...
<Text>{this.getCreds()}</Text>
HomeScreen.js
export const onSignIn = (username, pswd) => {
AsyncStorage.setItem('username', username).done();
AsyncStorage.setItem('pswd', pswd).done()
}
auth.js
<Text></Text>
in my render function?Your problem is that AsyncStorage.getItem as you may get by the name is an asynchronous call thereby you need to take that into account when calling it.
call it this way
constructor(props) {
super(props);
this.state = {username: null};
this.loadCredentials();
}
async loadCredentials() {
try {
const username = await AsyncStorage.getItem('username');
this.setState({username: username});
}
catch (error) {
// Manage error handling
}
}
render() {
const {username} = this.state;
if (username != null) {
return <Text>{username}</Text>
}
return <Text>Loading text...</Text>
}