What is the best way to store private data in react-native?

烈酒焚心 提交于 2019-11-27 05:21:53
Julien Kode

What is the best way to store private data in react-native?

I would recommend using a library like react-native-keychain to store private data in react-native

You can use it like that:

// Generic Password, service argument optional
Keychain
  .setGenericPassword(username, password)
  .then(function() {
    console.log('Credentials saved successfully!');
  });

// service argument optional
Keychain
  .getGenericPassword()
  .then(function(credentials) {
    console.log('Credentials successfully loaded for user ' + credentials.username);
  }).catch(function(error) {
    console.log('Keychain couldn\'t be accessed! Maybe no value set?', error);
  });

I hope my answer was helpful 😊

Expo.SecureStore provides a way to encrypt and securely store key–value pairs locally on the device.

Use SecureStore.setItemAsync(key, value, options) to store and SecureStore.getItemAsync(key, options) to retrieve data.

Documentation: https://docs.expo.io/versions/latest/sdk/securestore

You can use the simply storage of react-native to save the pair key=>value, the next class in TypeScript can help you:

export class MyStorage {

     handler: Storage;

    constructor(){
        this.handler = require('react-native-local-storage');
    }

    public saveData(key: string, value: string){
        this.handler.save(key,value).then(() => {
            this.handler.get(key).then((data) => {console.log("get: ", data)});

          })
    }

    public getData(key: string) : Promise<any> {        
      return this.handler.get(key);
    }

}
  • saveData method storage a "value" that can be accessed by a "key".
  • getData return the Promise that wrap the value saved with "key".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!