如何设置AsyncStorage的到期日期-React Native

艾哈迈德雕刻的莫斯塔法

我正在使用React Native异步存储,它可以正常工作,但是在某些情况下,我必须设置数据的到期日期并刷新我检查过的存储

AsyncStorage文档,但没有选项可设置在特定时间后过期。

仅可用的选项是:-

AsyncStorage.removeItem 
艾哈迈德雕刻的莫斯塔法

首先,我存储的是对象,而不是字符串,所以我的解决方案将基于对象的情况,如果有人使用字符串,他可以在对象键后附加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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章