Tell us some options of storing persisting data in a react native app?
Tell us some options of storing persisting data in a react native app?
In a React Native application, there are several options for storing and persisting data. Each method has its own advantages and is suitable for different use cases. Here are some of the most popular options:
AsyncStorage is an asynchronous, unencrypted, persistent, key-value storage system provided by React Native. It is suitable for storing small amounts of data, such as user preferences or authentication tokens. However, it is not recommended for large amounts of data or sensitive information due to its lack of encryption.
import AsyncStorage from '@react-native-async-storage/async-storage';
// Storing data
const storeData = async (value) => {
try {
await AsyncStorage.setItem('my-key', value);
} catch (e) {
// saving error
}
};
// Retrieving data
const getData = async () => {
try {
const value = await AsyncStorage.getItem('my-key');
if (value !== null) {
// value previously stored
}
} catch (e) {
// error reading value
}
};
SQLite is a lightweight, embedded SQL database that is widely used in mobile applications. It is suitable for applications that require complex queries and relational data storage. SQLite can handle larger datasets compared to AsyncStorage.
import { openDatabase } from 'react-native-sqlite-storage';
const db = openDatabase({ name: 'UserDatabase.db' });
db.transaction(function (txn) {
txn.executeSql(
'CREATE TABLE IF NOT EXISTS table_user(user_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name VARCHAR(20), user_contact INT(10), user_address VARCHAR(255))',
[]
);
});
Realm is an object-oriented database that is designed to run directly inside mobile applications. It is known for its performance and ease of use, especially for applications that require real-time data synchronization and complex data relationships.
import Realm from 'realm';
const UserSchema = {
name: 'User',
properties: {
name: 'string',
age: 'int',
},
};
const realm = new Realm({ schema: [UserSchema] });
realm.write(() => {
realm.create('User', { name: 'John', age: 30 });
});
React Native Storage is a wrapper around AsyncStorage that provides additional features such as size control, auto-expiring data, and remote data synchronization.
import Storage from 'react-native-storage';
import AsyncStorage from '@react-native-async-storage/async-storage';
const storage = new Storage({
size: 1000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
});
storage.save({
key: 'user',
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào