Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native store data between sessions

I need to store some user data, such as settings, login, token etc. between session. Tried asyncstorage but when I restart app, data in it gets deleted. Found some modules that refers to keychain or NSUserDefaults, but I don't know which and any of it is good for this purpose.
The main feature is that I can get that data even after app is killed and restarted. Mostly on iOS but if it would be also on Andorid, that would be great.
Anybody had some experience with it?

EDIT:
I tried using asyncstorage. But it doesn't do a thing when you kill and restart app.
My code for storing data:

 AsyncStorage.setItem("prefix", responseData['prefix'])
 AsyncStorage.setItem("api_token", responseData['api_token'])

And retrieving data:

async _checkAutoLogin(){ 
    var prefix;
    var token;
    try { 
       prefix = await AsyncStorage.getItem("prefix");
       token = await AsyncStorage.getItem("api_token"); 
} catch (error) { 
      AlertIOS.alert('AsyncStorage error: ' + error.message); 
    } 
like image 338
Michał Zubrzycki Avatar asked Nov 09 '15 15:11

Michał Zubrzycki


1 Answers

AsyncStorage should save your data to the device so that you can access it regardless of if your app has previously been sent to the background or has been cold launched. If you are trying to use the await keyword I think there is some extra setup that you will need to do to get it running. Here's a good article to get you going with that.

Also, depending on how much you intend on doing with AsyncStorage, the React Native site says this:

It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.

I've written a small wrapper around it called react-native-simple-store which just wraps up AsyncStorage and exposes a minimalistic API, but gives you JSON.stringifying and JSON.parsing by default for more complex values so you don't have to worry about it.

Or if you end up needing more of a local database there are other modules for that.

Hope that helps!

like image 51
jasonmerino Avatar answered Sep 30 '22 07:09

jasonmerino