2017-11-28 16 views
2

가 잘 작동 기본 비동기 저장 반응하지만, 어떤 경우에는 내가 데이터에 대한 만료 날짜를 설정하고 저장 용량을 새로 고쳐야 할 기본 반응 내가 확인- 내가 사용하고

AsyncStorage documentation하지만, 특정 시간 후에 만료되도록 설정할 수있는 옵션이 없습니다.

에만 사용할 수있는 옵션은 다음과 같습니다 -

AsyncStorage.removeItem 

답변

2

첫째, 객체를 저장하고, 문자열이 아니라 사람이 문자열을 그가 expireAt를 추가 할 수 있습니다 사용하는 오브젝트 키를 누른 그는 날짜를 만료 추출하고 현재 날짜

와 비교한다면 내 솔루션은 객체 케이스를 기반으로합니다 있도록 내 솔루션 : -

/** 
* 
* @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()으로 설정하십시오. 그런 다음 데이터를 가져올 때 만료시기를 기준으로 만료 키를 날짜 확인하십시오.