Beispiel #1
2
 static update(key, value, call) {
   AsyncStorage.mergeItem(
     key, value, () => (
       this.query(key, call)));
 }
'use strict';
/**
 * @overview A minimalistic wrapper around React Native's AsyncStorage.
 * @license MIT
 */
import { AsyncStorage } from 'react-native';

const deviceStorage = {
	/**
	 * Get a one or more value for a key or array of keys from AsyncStorage
	 * @param {String|Array} key A key or array of keys
	 * @return {Promise}
	 */
	get(key) {
		if(Array.isArray(key)) {
            return AsyncStorage.multiGet(key).then(values => {
                return values.map(value => {
                    return JSON.parse(value[1]);
                });
            });
		} else {
            return AsyncStorage.getItem(key).then(value => {
                return JSON.parse(value);
            });
		}
	},

	/**
	 * Save a key value pair to AsyncStorage.
	 * @param  {String|Array} key The key or an array of key/value pairs
	 * @param  {Any} value The value to save
Beispiel #3
0
 static get(key, callback) {
   AsyncStorage.getItem(key, callback);
 }
Beispiel #4
0
 /**
  * Adds a specific key to this storage and associates it with a specific
  * value. If the key exists already, updates its value.
  *
  * @param {string} key - The name of the key to add/update.
  * @param {string} value - The value to associate with {@code key}.
  * @returns {void}
  */
 setItem(key, value) {
     value = String(value); // eslint-disable-line no-param-reassign
     this[key] = value;
     typeof this._keyPrefix === 'undefined'
         || AsyncStorage.setItem(`${String(this._keyPrefix)}${key}`, value);
 }
Beispiel #5
0
import Quote from './../data/Quote';

const QUOTE_KEY = 'quoter-quotes';

var quotesStore = Reflux.createStore({
  init() {
    this._quotes = [];
    this._loadQuotes().done();

    this.listenTo(QuoteActions.createQuote, this.createQuote);
    this.listenTo(QuoteActions.clearAllQuotes, this.clearAllQuotes);
  },

  async _loadQuotes() {
    try {
      var val = await AsyncStorage.getItem(QUOTE_KEY);
      if (val === null) {
        console.info(`${QUOTE_KEY} not found on disk`)
        return;
      }

      this._quotes = JSON.parse(val)
        .map((quoteObj) => {
          return Quote.fromObject(quoteObj);
        });
        this.emit();
    } catch (error) {
      console.error(`AsyncStorage error: ${error.message}`);
    }
  },
Beispiel #6
0
                  (initialPosition) => {
                    ret.latitude = initialPosition.coords.latitude;
                    ret.longitude = initialPosition.coords.longitude;
                    AsyncStorage.setItem(DEVICE_KEY, JSON.stringify(ret));

                  },
Beispiel #7
0
 componentDidMount() {
   AsyncStorage.getItem('SET_REST_TIME').then(
     v => this.setState({ setRestTime: parseInt(v, 10) || SET_REST_TIME_DEFAULT })
   );
 }
Beispiel #8
0
import {AsyncStorage} from 'react-native';

export default {
  get(key) {
    return AsyncStorage.getItem(key)
      .then(JSON.parse)
      .catch(() => undefined);
  },
  multiGet(keys) {
    return AsyncStorage.multiGet(keys)
      .then((stores) => stores.reduce((keyValues, [key, value]) => {
        try {
          keyValues[key] = JSON.parse(value);
        } catch (e) {
          keyValues[key] = undefined;
        }
        return keyValues;
      }, {}));
  },
  set(key, value) {
    return AsyncStorage.setItem(key, JSON.stringify(value));
  },
  multiSet(keyValues) {
    return AsyncStorage.multiSet(
      Object.keys(keyValues).map((key) => [
        key,
        JSON.stringify(keyValues[key]),
      ])
    );
  },
  remove(key) {
Beispiel #9
0
 .then(menu => {
   return AsyncStorage.setItem('@XHUB:menu', JSON.stringify(menu));
 })
Beispiel #10
0
const saveCart = async (cartArray) => {
    await AsyncStorage.setItem('@cart', JSON.stringify(cartArray));
};
 storeExpirations() {
   AsyncStorage.setItem('expirations', JSON.stringify(this.state.expirations), () => {
     console.log("Successfully stored expiration list!");
   });
 }
Beispiel #12
0
  componentDidMount:function(){
    var that = this;
    this.setTimeout(//清理计时器 需要加入mixin FIXME
      ()=> {
        this.setState({splashed:false});
        //console.log(this.state);
    },2000);
    //异步任务去AsyncStroge中拿取 登录状态
    // 对于登录状态,暂时保存7天  如果不记住密码 保存30天 是有一个范围 TODO
    // async 约定保存格式 是 user$id:pass XXX
    // 正确格式是  loginStatus:user#password
    //  用来测试格式。。

    //only for test
    AsyncStorage.getItem('user_meta',function(error,result){
      console.log(arguments);
    });
    //两秒后完毕

    AsyncStorage.getItem('loginStatus',function(error,result){
      //错误出口优先。 error不出错的情况下一直是null  也就是不考虑error
      // 如果错误的话,那么。。。参数形式是[null,null]
      //var that = this;
      //console.log(arguments);


      //mock data   ***************************************************
    //   error = 1;
    //   result = 'dcy$dcy0701';


      //************************************************************
      if(result===null){  //这个 result是不为null的


        //说明未登录  那么 login=false
        this.setState({login:0});
        console.log(this.state.login);
        return;
      }
      // 否则 有登录信息 帮助用户登录
      // 在登录成功后,才改成 相应的状态码
      console.log(result);
      var username = result.split('$')[0];
      var password = result.split('$')[1];
      var expires = result.split('$')[2];
      // 判断登录信息是否过期。
      if (new Date().getTime()-604800000 > expires) {
        this.setState({login:0});
        return;
      }
      var fetch_url = config.API.LOGIN_API+'?user='******'&pass='******'fetch:'+fetch_url);


      fetch(fetch_url)
        .then(function(response){
          return response.json();
        })
        .then(function(json){
          console.log(JSON.stringify(json));

          if(json.user_name){
            //登录成功
            //that.setState({cover: result});
            this.setState({login: 3});
            AsyncStorage.setItem('user_meta',JSON.stringify(json),function(err){
              console.log(err);
            });
          }else{
            //登录失败 可能是密码错误等等
            this.setState({login:2});
          }
          //将用户元数据保存在 asyncStroge中
        }.bind(this));
    }.bind(this));
  },
Beispiel #13
0
           //that.setState({cover: result});
           this.setState({login: 3});
           AsyncStorage.setItem('user_meta',JSON.stringify(json),function(err){
             console.log(err);
           });
         }else{
           //登录失败 可能是密码错误等等
           this.setState({login:2});
         }
         //将用户元数据保存在 asyncStroge中
       }.bind(this));
   }.bind(this));
 },
 logout(){
   AsyncStorage.removeItem('loginStatus',function(err){
     console.log(err);
   }).then(function(){
     console.log('!!!!调用了退出,传递给了index');
     this.setState({login:0});
   }.bind(this));
 },
 render: function() {
   if (this.state.splashed||this.state.login==1) {
     return (
       //这里是载入动画 done FIXME
       <SplashScreen />
     );
   }else if(this.state.login==2||this.state.login==0){
     return (
         <Login status={this.state.login}/>
       //这里是 登录页面 TODO
		return deviceStorage.get(key).then(item => {
			value = typeof value === 'string' ? value : Object.assign({}, item, value);
			return AsyncStorage.setItem(key, JSON.stringify(value));
		});
 /**
  * Clear all session data (logout)
  */
 async clear() {
   await AsyncStorage.removeItem(namespace + 'access_token');
   await AsyncStorage.removeItem(namespace + 'private_key');
 }
Beispiel #16
0
  saveData(key, value) {
    console.log('key: ' + key + ' value: ' + value);

    this.setState({[key]: value});
    AsyncStorage.setItem(key, value).done();
  }
Beispiel #17
0
 return (dispatch, getState) => {
   const auth = getState().auth
   return AsyncStorage.setItem('auth', JSON.stringify(auth))
 }
Beispiel #18
0
const DECK_KEY = 'total-recall-decks'

const decksStore = Reflux.createStore({
  init() {
    this.decks = []
    this.loadDecks().done()
    this.cards = []
    this.listenTo(CardsStore,                 this.cardUpdate)
    this.listenTo(DeckActions.createDeck,     this.createDeck)
    this.listenTo(DeckActions.deleteAllDecks, this.deleteAllDecks)
  },

  async loadDecks() {
    try {
      const val = await AsyncStorage.getItem(DECK_KEY)

      if (val !== null) {
        this.decks = JSON.parse(val).map(deckObj => Deck.fromObject(deckObj))
        this.emit()
      } else {
        console.info(`${DECK_KEY} not found on disk.`);
      }
    } catch (e) {
      console.error('AsyncStorage error:', e.message);
    }
  },

  async writeDecks() {
    try {
      await AsyncStorage.setItem(DECK_KEY, JSON.stringify(this.decks))
Beispiel #19
0
 (error) => {
   AsyncStorage.setItem(DEVICE_KEY, JSON.stringify(ret));
 },
 logout : function () {
   AsyncStorage.removeItem("aroundUser");
   this.setState({user:{}});
 },
Beispiel #21
0
 /**
  * Removes a specific key from this storage.
  *
  * @param {string} key - The name of the key to remove.
  * @returns {void}
  */
 removeItem(key) {
     delete this[key];
     typeof this._keyPrefix === 'undefined'
         || AsyncStorage.removeItem(`${String(this._keyPrefix)}${key}`);
 }
Beispiel #22
0
 logout() {
   AsyncStorage.clear();
   this.props.navigator.pop();
 }
Beispiel #23
0
 _signInAsync = async () => {
   await AsyncStorage.setItem('userToken', 'abc');
   this.props.navigation.navigate('App');
 };
 /**
  * Set access token
  * @param {string} token
  * @param {string} guid
  */
 setAccessToken(token, guid) {
   return AsyncStorage.setItem(namespace + 'access_token', JSON.stringify({token, guid}));
 }
Beispiel #25
0
 static set(key, value) {
   AsyncStorage.setItem(key, value);
 }
 /**
  * Set private key
  * @param {string} privateKey
  */
 setPrivateKey(privateKey) {
   AsyncStorage.setItem(namespace + 'private_key', privateKey);
 }
Beispiel #27
0
 static del(key, call) {
   AsyncStorage.removeItem(
     key, () => (
       this.query(key, call)));
 }
 /**
  * Clear messenger private keys
  */
 clearPrivateKey() {
   return AsyncStorage.removeItem(namespace + 'private_key');
 }
Beispiel #29
0
 static query(key, call) {
   AsyncStorage.getItem(
     key, (err, result) => (
       call(result)));
 }
 /**
  * Set selected localeName, eg: sv, en, dk
  * @param {string} localeName
  * @return {Promise} Returns AsyncStorage promise
  */
 async setSelectedLocaleWithLocaleName(localeName) {
     return AsyncStorage.setItem(this.selectedLocaleNameStorageKey, localeName);
 }