项目作者: abdelav

项目描述 :
A local storage wrapper for both react-native(AsyncStorage) and browser(localStorage).
高级语言: JavaScript
项目地址: git://github.com/abdelav/react-hybrid-storage.git
创建时间: 2017-07-21T04:04:29Z
项目社区:https://github.com/abdelav/react-hybrid-storage

开源协议:MIT License

下载


react-hybrid-storage Build Status

A local storage wrapper for both react-native(AsyncStorage) and browser(localStorage).

Features

  • Promise based for async load.
  • Size controlling.
  • Auto expiring.
  • Remote data auto syncing.
  • Get a batch data in one query.

Install

in react-native environment require react-native version >= 0.13

  1. npm install react-hybrid-storage --save OR yarn add react-hybrid-storage

Usage

Import

  1. import Storage from 'react-hybrid-storage';

Do not use require('react-hybrid-storage'), which would cause error in react-native version >= 0.16.

Init

  1. import Storage from 'react-hybrid-storage';
  2. import { AsyncStorage } from 'react-native'; // Don't import if the target is web
  3. const storage = new Storage({
  4. size : 1000, // maximum capacity, default 1000
  5. storageBackend : AsyncStorage, // Use AsyncStorage for RN, or window.localStorage for web.
  6. defaultExpires : 1000 * 3600 * 24, // expire time, default 1 day(1000 * 3600 * 24 milliseconds).
  7. enableCache : true, // cache data in the memory. default is true.
  8. sync : {},
  9. })
  10. // I suggest you have one(and only one) storage instance in global scope.
  11. // for web
  12. window.storage = storage;
  13. // for react-native
  14. global.storage = storage;

Save

  • key : should be an unique string value and are permanently stored unless you remove, do not use underscore(“_”) in key!
  • data : any valid JSON object to save.
  • expires : expire time in milliseconds, if set to null, then it will never expire.
  1. storage.save({
  2. key : 'auth',
  3. data : {
  4. token : 'some access token',
  5. refresh : 'some refresh token',
  6. },
  7. expires : 1000 * 3600,
  8. });

Load

  • key : a string value (key) that we want to load.
  • autoSync : if data not found or expired, then invoke the corresponding sync method.
  • syncInBackground : if data expired, return the outdated data first while invoke the sync method.
  • syncParams : you can pass extra params to sync method.
  1. try {
  2. const { token, refresh } = await storage.load({
  3. key : 'auth',
  4. autoSync : true,
  5. syncInBackground : true,
  6. syncParams : {},
  7. });
  8. console.log(token);
  9. } catch (error) {
  10. // Do something
  11. }

Credits

This library is a rewrite of react-native-storage originally created by sunnylqm. We really appreciate the effort he did solving the issue we face using localstorage and async storage in multiplatform enviorments.

License

MIT