react-native-storage
![npm version](https://badge.fury.io/js/react-native-storage.svg)
This is a local storage wrapper for both mobile React-Native apps (using AsyncStorage) and React browser-invoked web apps (using 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.
Add the following lines to your webpack config:
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 React Native version >= 0.13 is required).
Import
import Storage from 'react-native-storage';
Do not use require('react-native-storage')
, which will cause an error in react native version >= 0.16.
Init
import Storage from 'react-native-storage';
import { AsyncStorage } from 'react-native';
var storage = new Storage({
size: 1000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync : {
}
})
Save & Load & Remove
storage.save({
key: 'loginState',
data: {
from: 'some other site',
userid: 'some userid',
token: 'some token'
},
expires: 1000 * 3600
});
storage.load({
key: 'loginState',
autoSync: true,
syncInBackground: true,
syncParams: {
extraFetchOptions: {
},
someFlag: true,
},
}).then(ret => {
console.log(ret.userid);
}).catch(err => {
console.warn(err.message);
switch (err.name) {
case 'NotFoundError':
break;
case 'ExpiredError':
break;
}
})
var userA = {
name: 'A',
age: 20,
tags: [
'geek',
'nerd',
'otaku'
]
};
storage.save({
key: 'user',
id: '1001',
data: userA,
expires: 1000 * 60
});
storage.load({
key: 'user',
id: '1001'
}).then(ret => {
console.log(ret.userid);
}).catch(err => {
console.warn(err.message);
switch (err.name) {
case 'NotFoundError':
break;
case 'ExpiredError':
break;
}
});
storage.getIdsForKey('user').then(ids => {
console.log(ids);
});
storage.getAllDataForKey('user').then(users => {
console.log(users);
});
storage.clearMapForKey('user');
storage.remove({
key: 'lastPage'
});
storage.remove({
key: 'user',
id: '1001'
});
storage.clearMap();
Sync remote data(refresh)
There are two ways to set the sync method.
You can pass the sync method in the constructor's parameter, as a function in an object,
or you can define it at any time as shown below:
storage.sync = {
user(params){
let { id, resolve, reject, syncParams: { extraFetchOptions, someFlag } } = params;
fetch('user/', {
method: 'GET',
body: 'id=' + id,
...extraFetchOptions,
}).then(response => {
return response.json();
}).then(json => {
if(json && json.user){
storage.save({
key: 'user',
id,
data: json.user
});
if (someFlag) {
}
resolve && resolve(json.user);
}
else{
reject && reject(new Error('data parse error'));
}
}).catch(err => {
console.warn(err);
reject && reject(err);
});
}
}
In the following example the sync method is called, when you invoke storage.load
:
storage.load({
key: 'user',
id: '1002'
}).then(...)
If there is no user 1002 currently in storage, then storage.sync.user will be invoked to fetch and return the remote data.
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 an important difference between the way these two methods perform:
getBatchData will invoke separate sync methods for each different key one after the other when the corresponding data is missing or not in sync. However, getBatchDataWithIds will collect a list of the missing data, pushing their ids to an array, and then pass the array to the single corresponding sync method once, reducing the number of requests, so you need to implement array query on the server side and handle the parameters of sync method properly. Note that 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.2.2
- check key availability in clearMapForKey
0.2.0
rawData
is now deprecated, use "data" instead!- Upgrade jest to 19.0.0
0.1.5
- Now you can pass extra params to sync method.
- Fix clearMap
0.1.4
- Now you can check error type (NotFoundError and ExpiredError) in catch
- Optimize cache strategy
0.1.3
- Now you need to specify storageBackend(AsyncStorage or window.localStorage), otherwise the data would not be persisted.
0.1.2
- Now when load() failed to find data, it will throw an Error with message instead of undefined.
0.1.1
defaultExpires
can be null
now, which means never expire.
0.1.0
- add getIdsForKey, getAllDataForKey, clearMapForKey methods
- fix some expires logic
- refactor unit tests
0.0.16
- getBatchDataWithIds now won't invoke sync if everything is ready in storage.
0.0.15
- 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.