AsyncStorage.getItem("item") returns the string "[object Object]"

I'm using AsyncStorage in order to save a "session" in my app, and I do so in this piece of code:

if (signInResult) {
    if (signInResult.userId && signInResult.accessToken) {
        await AsyncStorage.setItem("auth", signInResult);
    }
    this.props.navigation.navigate("home");
}

But when I tried to get the data back with AsyncStorage.getItem("auth"), it just retrieves the string [object Object]

I tweaked the code a but to write stuff in the console so I could keep tabs on the data, so here's what I encountered so far:

enter image description here

Console

So there I logged the same data before and after putting it "through" the AsyncStorage. First, we see that the object is still very much a javascript object, and the second is just the name o the type, apparently. I'm not sure what's going on here, but I'm pretty sure this should work. I actually use that same approach in another app and I don't have this issue there.

Thanks in advance.

Upvotes: 0

Views: 871

Answers (1)

Rajan
Rajan

Reputation: 1568

You need to JSON.stringify & JSON.parse while saving and getting data from AsyncStorage.

if (signInResult) {
  if (signInResult.userId && signInResult.accessToken) {
    await AsyncStorage.setItem("auth", JSON.stringify(signInResult));
  }
  AsyncStorage.getItem("auth").((item) => {
    JSON.parse(item);
  });

  this.props.navigation.navigate("home");
}

Upvotes: 1

Related Questions