react-native-storage
This is a local storage wrapper for both react-native(AsyncStorage) and browser(localStorage). ES6 syntax, promise for async load, fully tested with jest.
查看中文文档请点击README-CHN.md
Install
npm install react-native-storage --save
Usage
Config
For Web
You need to use webpack and babel to enable es6 modules for web development.
You should add the following lines to your webpack config:
externals: {
"react-native": {}
},
module: {
loaders: [
{
test: /\.js?$/,
include: [
path.join(__dirname, 'node_modules/react-native-storage')
],
loader: 'babel',
query: {
cacheDirectory: true,
presets: ['es2015', 'stage-1', 'react'],
plugins: ['transform-runtime']
}
}
]
}
For React Native
You don't have to configure anything(but require react native version >= 0.13).
Import
import Storage from 'react-native-storage';
Do not use require('react-native-storage')
, which would cause error in version 0.16.
Init
var storage = new Storage({
size: 1000,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync : {
}
})
Save & Load & Remove
storage.save({
key: 'loginState',
rawData: {
from: 'some other site',
userid: 'some userid',
token: 'some token'
},
expires: 1000 * 3600
});
storage.load({
key: 'loginState',
autoSync: true,
syncInBackground: true
}).then( ret => {
console.log(ret.userid);
}).catch( err => {
console.warn(err);
})
var userA = {
name: 'A',
age: 20,
tags: [
'geek',
'nerd',
'otaku'
]
};
storage.save({
key: 'user',
id: '1001',
rawData: userA,
expires: 1000 * 60
});
storage.load({
key: 'user'
id: '1001'
}).then( ret => {
console.log(ret.userid);
}).catch( err => {
console.warn(err);
})
storage.remove({
key: 'lastPage'
});
storage.remove({
key: 'user'
id: '1001'
});
storage.clearMap();
Sync remote data(refresh)
You can pass sync methods as one object parameter to the storage constructor, but also you can add it any time.
storage.sync = {
user(params){
let { id, resolve, reject } = params;
fetch('user/', {
method: 'GET',
body: 'id=' + id
}).then( response => {
return response.json();
}).then( json => {
if(json && json.user){
storage.save({
key: 'user',
id,
rawData: json.user
});
resolve && resolve(json.user);
}
else{
reject && reject('data parse error');
}
}).catch( err => {
console.warn(err);
reject && reject(err);
});
}
}
With this example sync method, when you invoke:
storage.load({
key: 'user',
id: '1002'
}).then(...)
If there is no user 1002 stored currently, then storage.sync.user would be invoked to fetch remote data and returned.
Load batch data
storage.getBatchData([
{ key: 'loginState' },
{ key: 'checkPoint', syncInBackground: false },
{ key: 'balance' },
{ key: 'user', id: '1009' }
])
.then( results => {
results.forEach( result => {
console.log(result);
})
})
storage.getBatchDataWithIds({
key: 'user',
ids: ['1001', '1002', '1003']
})
.then( ... )
There is a notable difference between the two methods except the arguments. getBatchData will invoke different sync methods(since the keys may be different) one by one when corresponding data is missing. However, getBatchDataWithIds will collect missing data, push their ids to an array, then pass the array to the corresponding sync method(to avoid too many requests) once, so you need to implement array query on server end and handle the parameters of sync method properly(cause the id parameter can be a single string or an array of strings).
####You are welcome to ask any question in the issues page.
Changelog
0.0.14
- Fix bugs in promise chain.
- Can be used without any storage backend.(Use in-memory map)
0.0.10
- All methods except remove and clearMap are now totally promisified. Even custom sync methods can be promise. So you can chain them now.
- Adjust map structure.
- Improved some test cases.