Reputation: 813
How to store/save data in react native.Like we use shared-preference in android, is there any solution for react native.I am new to react-nactive.
please add sample example
Upvotes: 14
Views: 22572
Reputation: 1889
You can use React Native AsyncStorage for storing data to local storage of the device.
import AsyncStorage from '@react-native-async-storage/async-storage';
Use this to save data
AsyncStorage.setItem('key', 'value');
AsyncStorage accepts value as only string, so you may need to use JSON.stringify()
before setting the value to AsyncStorage
And to retrieve data use
AsyncStorage.getItem('key');
Example Code :
const KEY = 'USER_DATA'
let value = { name: yogi }
AsyncStorage.setItem(KEY, value);
AsyncStorage.getItem(KEY).then(asyncStorageRes => {
console.log(JSON.parse(asyncStorageRes))
});
For sensitive data such as access tokens, payment information, etc. you may wish to use EncryptedStorage
import EncryptedStorage from 'react-native-encrypted-storage';
It uses a similar API to AsyncStorage so you can use the following to save and retrieve data:
EncryptedStorage.setItem('key', 'value');
EncryptedStorage.getItem('key');
There are of course other storage options to choose from too.
Upvotes: 26
Reputation:
used Async storage class to stored and retrive data in react native
Upvotes: 1
Reputation: 121
you can use react-native-easy-app that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.
export const RNStorage = {// RNStorage : custom data store object
token: undefined, // string type
isShow: undefined, // bool type
userInfo: undefined, // object type
};
import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';
XStorage.initStorage(RNStorage, AsyncStorage, () => {
... // RNStorage 【Property access code snippet】
});
// OR ---------------------------------------------------------------
const result = await XStorage.initStorageSync(RNStorage, AsyncStorage);
if (result) {
... // RNStorage 【Property access code snippet】
}
// RNStorage 【Property access code snippet】
// From now on, you can write or read the variables in RNStorage synchronously
console.log(RNStorage.isShow);
// equal to [console.log(await AsyncStorage.getItem('isShow'))]
RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3==';
// equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]
RNStorage.userInfo = {name: 'rufeng', age: 30};
// equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
Upvotes: -1
Reputation: 2819
React Native also have shared preferences this is npm command to get it: npm install react-native-shared-preferences --save
. You can get complete details(how to set it up in react project) here: https://www.npmjs.com/package/react-native-shared-preferences
Upvotes: 4