Ahm*_*afa 4 react-native asyncstorage
我正在使用 react native async storage 它运行良好,但在某些情况下,我必须为数据设置到期日期并刷新我检查过的存储
AsyncStorage 文档,但没有设置在特定时间后过期的选项。
唯一可用的选项是:-
AsyncStorage.removeItem
Run Code Online (Sandbox Code Playgroud)
AsyncStorage 实际上只处理存储,除此之外别无他物。
如果您想设置过期时间,只需在您的数据中输入一个访问日期的密钥并将其设置为new Date()。然后,当您提取数据时,根据到期时间对到期密钥进行日期检查。
首先,我存储的是对象,而不是字符串,所以我的解决方案将基于对象大小写,如果有人使用他可以附加 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7490 次 |
| 最近记录: |