Search code examples
react-nativeasyncstorage

AsyncStorage has weird characters in React-Native


I'm trying to store my users authorization key using AsyncStorage but whenever I do I get weird characters. Here is my relevant code:

async function retrieveItem(key) {
    try {
        let retrievedItem =  await AsyncStorage.getItem(key).then(value => retrieveItem = value);
        return retrievedItem;
    } catch (error) {
        console.log(error.message);
    }   
    return
}

let test = retrieveItem('@authentication')

class AppNavigation extends Component {
    render() {
        console.log(test)
...

This is the output that I get for test. The item that I want is there under _55 and I'm able to get it by doing console.log(test._55). I just wanted to make sure I am not doing this correctly. Will the key always be _55 for async storage?

{"_40": 0, "_55": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTk1ODM3NDJlZDI1YjAxMWM4MWFiNWEiLCJpYXQiOjE1ODY4NTY4MjB9.yK0WYuZj7_2Nih7phisi5rmm0y7gF__PMRMEAafIkFk", "_65": 1, "_72": null}

Solution

  • You should note use async/await and .then together, both do the same thing. Try this code instead:

    async function retrieveItem(key) {
        try {
            let retrievedItem =  await AsyncStorage.getItem(key);
            return retrievedItem;
        } catch (error) {
            console.log(error.message);
        }   
        return
    }
    
    let test = await retrieveItem('@authentication')
    
    class AppNavigation extends Component {
        render() {
            console.log(test)
    

    Edit: the object you got is a promise and you can get its value by doing the async/await syntax or calling .then(...)