Hướng dẫn dùng react-native-async-storage/async-storage JavaScript
Show AsyncStorage là thành phần đơn giản dùng để lưu trữ dữ liệu offline. Nó hỗ trợ lưu trữ dữ liệu không mã hóa theo dạng cặp key-value và hỗ trợ bất đồng bộ Chúng ta có thể lưu dữ liệu độ lớn tùy thuộc vào bộ nhớ của máy do AsyncStorage sẽ tự động sử dụng “Dictionary” hoặc File để lưu giá trị (iOS) hoặc sử dụng RocksDB, Sqlite (Android) Để sử dụng AsyncStorage chúng ta chỉ cần 2 hàm đơn giản sau :
Từ ví dụ trên chúng ta giải thích các câu lệnh như sau : Cách lưu dữ liệu : AsyncStorage.setItem(‘TASKS’, ‘I like to save it.’) Cách lấy dữ liệu : AsyncStorage.getItem(‘TASKS’) . Bài tập : Sinh viên tạo 1 màn hình Login với 2 TextInput nhập Username và Password. 1 Button Login và 1 checkbox “Nhớ mật khẩu” sử dụng AsyncStorage để lưu tài khoản đã đăng nhập
It is recommended that you use an abstraction on top of On iOS, The Importing the
Persisting data:
Fetching data:
ReferenceMethodsgetItem()
Fetches an item for a
Parameters:
setItem()
Sets the value for a Parameters:
removeItem()
Removes an item for a Parameters:
mergeItem()
Merges an existing NOTE: This is not supported by all native implementations. Parameters:
Example:
|
Name | Type | Required | Description |
---|---|---|---|
callback | ?(error: ?Error) => void
| No | Function that will be called with any error. |
getAllKeys()
static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)
Gets all keys known to your app; for all callers, libraries, etc. Returns a Promise
object.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
callback | ?(error: ?Error, keys: ?Array
| No | Function that will be called with all keys found and any error. |
flushGetRequests()
static flushGetRequests(): [object Object]
Flushes any pending requests using a single batch call to get the data.
multiGet()
static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<string>>) => void)
This allows you to batch the fetching of
items given an array of key
inputs. Your callback will be invoked with an array of corresponding key-value pairs found:
multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])
The method returns a Promise
object.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
keys | Array
| Yes | Array of key for the items to get. |
callback | ?(errors: ?Array
| No | Function that will be called with a key-value array of the results, plus an array of any key-specific errors found. |
Example:
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
stores.map((result, i, store) => {
// get at each store's key/value so you can work with it
let key = store[i][0];
let value = store[i][1];
});
});
});
multiSet()
static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)
Use this as a batch operation for storing multiple key-value pairs. When the operation completes you'll get a single callback with any errors:
multiSet([['k1', 'val1'], ['k2', 'val2']], cb);
The method returns a Promise
object.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
keyValuePairs | Array
| Yes | Array of key-value array for the items to set. |
callback | ?(errors: ?Array
| No | Function that will be called with an array of any key-specific errors found. |
multiRemove()
static multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)
Call this to batch the deletion of all keys in the keys
array. Returns a Promise
object.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
keys | Array
| Yes | Array of key for the items to delete. |
callback | ?(errors: ?Array
| No | Function that will be called an array of any key-specific errors found. |
Example:
let keys = ['k1', 'k2'];
AsyncStorage.multiRemove(keys, (err) => {
// keys k1 & k2 removed, if they existed
// do most stuff after removal (if you want)
});
multiMerge()
static multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)
Batch operation to merge in existing and new values for a given set of keys. This assumes that the values are stringified JSON. Returns a Promise
object.
NOTE: This is not supported by all native implementations.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
keyValuePairs | Array
| Yes | Array of key-value array for the items to merge. |
callback | ?(errors: ?Array
| No | Function that will be called with an array of any key-specific errors found. |
Example:
// first user, initial values
let UID234_object = {
name: 'Chris',
age: 30,
traits: { hair: 'brown', eyes: 'brown' }
};
// first user, delta values
let UID234_delta = {
age: 31,
traits: { eyes: 'blue', shoe_size: 10 }
};
// second user, initial values
let UID345_object = {
name: 'Marge',
age: 25,
traits: { hair: 'blonde', eyes: 'blue' }
};
// second user, delta values
let UID345_delta = {
age: 26,
traits: { eyes: 'green', shoe_size: 6 }
};
let multi_set_pairs = [
['UID234', JSON.stringify(UID234_object)],
['UID345', JSON.stringify(UID345_object)]
];
let multi_merge_pairs = [
['UID234', JSON.stringify(UID234_delta)],
['UID345', JSON.stringify(UID345_delta)]
];
AsyncStorage.multiSet(multi_set_pairs, (err) => {
AsyncStorage.multiMerge(multi_merge_pairs, (err) => {
AsyncStorage.multiGet(['UID234', 'UID345'], (err, stores) => {
stores.map((result, i, store) => {
let key = store[i][0];
let val = store[i][1];
console.log(key, val);
});
});
});
});
// Console log results:
// => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}}
// => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}}