4

I am building an Android app and I am struggling using the AsyncStorage. I want to create a function that takes a key as input and give me back the item. My problem is that when I call this function, it returns { _40: 0, _65: 0, _55: null, _72: null } instead the value I am looking for.

Here is my code :

renderList() {

    async function save() {
        await AsyncStorage.setItem('Title', 'hello');
    }

    async function fetch(key) {
        const value = await AsyncStorage.getItem(key);
        console.log(value) ; // Return hello
        return value
    }

    save() ;
    fetch() ;

    const reponse = fetch() ;
    console.log(reponse) ; // Return { _40: 0, _65: 0, _55: null, _72: null }

    return (
        <Text style={styles.noteElementTitle}> Aa </Text>
    )
}

Edit :

I tried this :

    async function getBody() {
    await save();
    const response = await fetch('Title');
    console.log(response);
    this.setstate({ title : response}) ;
    }

    getBody() ;

But I still get an error : TypeError: undefined is not a function (evaluating 'this.setstate({ title: response })')

Audeo
  • 87
  • 2
  • 7
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Michael Cheng Sep 25 '17 at 15:08
  • First guess is that. Second is that it's possibly due to no passing in a value for `key` to your `fetch()` call. I'll attempt to reproduce this but these two things are a starting point for you. – Michael Cheng Sep 25 '17 at 15:11
  • Looks like someone answered and my first hunch was correct. It's a duplicate. Take some time to read both the answer and the one I linked. It'll help you avoid many similar errors in the future. – Michael Cheng Sep 25 '17 at 15:18

1 Answers1

8

What you're seeing is the Promise object returned by a function marked async. You need to either use await when calling the function, or treat the value as a promise and use then and catch. For example:

await save();
const response = await fetch();
console.log(response);

or

save()
  .then(() => fetch())
  .then(response => console.log(response));

Also, keep in mind that you should not be using async functions inside a render function. In your code above, you'll want to put the result of your fetch() function into component state.

A. Goodale
  • 1,288
  • 11
  • 13