我如何为 AsyncStorage 设置到期日期 - 反应原生 [英] How I can set expiration date for AsyncStorage - react native

查看:95
本文介绍了我如何为 AsyncStorage 设置到期日期 - 反应原生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Native 异步存储,它运行良好,但在某些情况下,我必须为数据设置到期日期并刷新我检查过的存储

I am using react native async storage it works good but in some cases, I have to set an expiration date for data and refresh my storage I checked

AsyncStorage 文档 但没有设置过期时间的选项特定时间.

AsyncStorage documentation but there are no options to set expire after a specific time.

只有可用的选项是:-

AsyncStorage.removeItem 

推荐答案

首先,我存储的是对象,而不是字符串,所以我的解决方案将基于对象案例,如果有人使用他可以附加的字符串,他可以在对象键上附加 expireAt 对象键,然后他将提取过期日期并与当前日期进行比较

first, I am storing objects, not strings so my solution will be based on object case if anyone uses strings he can append expireAt the object key then he will extract expire date and compare it with the current date

我的解决方案:-

/**
 *
 * @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;
}

这篇关于我如何为 AsyncStorage 设置到期日期 - 反应原生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆