Search code examples
react-nativeasyncstorage

How I can set expiration date for 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 documentation but there are no options to set expire after a specific time.

only available options are:-

AsyncStorage.removeItem 

Solution

  • 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

    my solution:-

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