Michał Zubrzycki
Michał Zubrzycki

Reputation: 885

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); 
    } 

Upvotes: 8

Views: 9723

Answers (4)

ast
ast

Reputation: 526

There is also Realm for React Native which gives you a full local database: https://realm.io

Upvotes: 0

jasonmerino
jasonmerino

Reputation: 3240

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!

Upvotes: 10

SrvfUser
SrvfUser

Reputation: 410

This works even after restarting the app:

  _login:function(token){
    AsyncStorage.setItem('ApiToken',token,
      () => this.setState({isLoggedIn:true}),
      (error) => console.log(error)
    );
  },

Upvotes: 0

Zygro
Zygro

Reputation: 7119

https://facebook.github.io/react-native/docs/asyncstorage.html#content might do the trick. It says that it's persistent storage which probably means the quality you are looking for.

Upvotes: 0

Related Questions