Search code examples
javascriptreactjsreact-nativeasyncstorage

Async Storage retrieve value of key in item


I'm new to Javascript and react native, and the question itself will be probably very easy to answer.

I'm setting up a AsyncStorage and creating a Item inside the storage, which is a .JSON that has 3 key values to it.

const saveDataToStorage = (token, userId, expirationDate) => { 
  AsyncStorage.setItem('userData', JSON.stringify({
    token: token, 
    userId: userId,
    expiryDate: expirationDate.toISOString()
  }))
};

What I want to do now is to retrieve the "userId" value from this item in an other part of the project but here is the problem.

var PersonalId = await AsyncStorage.getItem('userData');
console.log(PersonalId);
console.log(typeof PersonalId);

I know how to access the item itself, but I have no clue how to access the special key inside it. I can not use the command:

var PersonalId = await AsyncStorage.getItem('userData').userId;

because the item from the AsyncStorage is a string, I know this because I got this info from the second line of my code.

console.log(typeof PersonalId);

How can I access the special key "userId" inside my item "userData" and not the whole item itself? I cant work with the item anyways because its a string, I can not treat it as an object and thats my problem.

Thank you for reading and helping out!


Solution

  • You are forgetting that you stringified the JSON before saving it to storage.. so you are getting string when you read it. Simply JSON.parse the returned string and you should be on your way.

    const userData = await AsyncStorage.getItem('userData');
    const personalId = JSON.parse(userData).userId;
    

    You should also wrap the above code in a try-catch to make sure you catch errors when invalid data is tried to be parsed and it throws an error.