Search code examples
javascriptreact-nativeasyncstorage

Get AsyncStorage data to <Text></Text>


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.

Code to get data

getCreds = () => {
    return AsyncStorage.getItem('username')
}
...
<Text>{this.getCreds()}</Text>

HomeScreen.js

Code to store the data

export const onSignIn = (username, pswd) => {
  AsyncStorage.setItem('username', username).done();
  AsyncStorage.setItem('pswd', pswd).done()
}

auth.js

My question is how can I get the username from AsyncStorage and parse into a <Text></Text> in my render function?


Solution

  • 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>
    }