0
votes

I add the setItem function of AsyncStorage in the constructor of my Component and then I made a function to fetch it's value using the getItem function, but it returns empty. Am I missing something?

Here's my code:

constructor(props) {
    super(props);
    try {
        AsyncStorage.setItem('testKey', 'I like to save it.');
    } catch (error) {
        alert("error", error);
        // Error saving data
    }
}

getData(){
    AsyncStorage.getItem('testKey').then((data) => {
        alert("data", data);
    })
}

Basically, I want to store an accessToken to AsyncStorage, and once it's set, I want to call the getItem function to use it.

Also, the then() function for the setItem is not working:

AsyncStorage.setItem('testKey','blah blah').then(() => {
  console.log("I never get executed."); // -> this code never executes for some reason
});

I've been trying to resolve it, but to no avail.

1
Two different issues here. You really should break this up into two separate questions. For both, more context is needed. re: 1st issue - How and when are you calling getData()? setItem is asynchronous so depending on when you call getData(), setItem may not have finished executing. re: 2nd issue - needs more code. By itself, it's literally impossible for someone to reproduce the error as just that line of code works for me. - Michael Cheng
getData() is called using onPress of a button/touchableopacity. This is all the code I'm running, except the above, it includes imports, a component declaration class within which those functions exist and render() containing the button that has the onPress function as getData() - Ketan Malhotra

1 Answers

1
votes

Keep in mind that both (setItem and getItem) are executed asynchronous, a async/await should solve your problem, as explained in the documentation:

constructor(props) {
    super(props);
    this.setData();
}

async setData() {
    try {
        await AsyncStorage.setItem('testKey', 'I like to save it.');
    } catch (error) {
        // Error setting data
    }
}

async getData(){
    try {
        const value = await AsyncStorage.getItem('testKey');
        if (value) {
            // We have data!!
            console.log(value);
        }
    } catch (error) {
        // Error retrieving data
    }
}