2017-11-28 7 views
2

を反応させるには、ネイティブ非同期ストレージを反応させ、私は- 私が使用しているネイティブ

AsyncStorage documentationをチェックし、それが良い動作しますが、いくつかのケースでは、私は、データの有効期限を設定し、私の記憶をリフレッシュする必要がなく、特定の時間の後に有効期限を設定するオプションはありません。

のみ利用可能なオプションは次のとおりです。 -

AsyncStorage.removeItem 

答えて

2

最初、私はオブジェクトではなく、文字列を格納しています私の解決策: -

/** 
* 
* @param urlAsKey 
* @param expireInMinutes 
* @returns {Promise.<*>} 
*/ 
async getCachedUrlContent(urlAsKey, expireInMinutes = 60) { 

    let data = null; 

    await AsyncStorage.getItem(urlAsKey, async (err, value) => { 

     data = (JSON.parse(value)); 

     // there is data in cache && cache is expired 
     if (data !== null && data['expireAt'] && 
      new Date(data.expireAt) < (new Date())) { 

      //clear cache 
      AsyncStorage.removeItem(urlAsKey); 


      //update res to be null 
      data = null; 
     } else { 

      console.log('read data from cache '); 

     } 
    }); 

    //update cache + set expire at date 
    if (data === null) { 
     console.log('cache new Date '); 

     //fetch data 
     data = fetch(urlAsKey).then((response) => response.json()) 
      .then(apiRes => { 

       //set expire at 
       apiRes.expireAt = this.getExpireDate(expireInMinutes); 

       //stringify object 
       const objectToStore = JSON.stringify(apiRes); 

       //store object 
       AsyncStorage.setItem(urlAsKey, objectToStore); 


       console.log(apiRes.expireAt); 
       return apiRes; 
      }); 

    } 

    return data; 


}, 

/** 
* 
* @param expireInMinutes 
* @returns {Date} 
*/ 
getExpireDate(expireInMinutes) { 
    const now = new Date(); 
    let expireTime = new Date(now); 
    expireTime.setMinutes(now.getMinutes() + expireInMinutes); 
    return expireTime; 
} 
2

AsyncStorageは本当に唯一のそれを超えて保管し、何を処理します。

有効期限を設定する場合は、データにアクセス日のキーを入力してnew Date()に設定します。次に、データをプルするときに、期限切れになる期限に基づいて期限切れキーを日付チェックします。私の解決策は、誰もが文字列を使用している場合、彼はexpireAtにオブジェクトキーを追加することができ、その後、彼は有効期限を抽出し、現在の日付

とそれを比較するオブジェクトのケースに基づいて行われますので、

関連する問題