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
AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system.
Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.
Motivation Current Async Storage's size is set to 6MB. Going over this limit causes database or disk is full error. This 6MB limit is a sane limit to protect the user from the app storing too much data in the database.
AsyncStorage really only handles storage and nothing beyond that.
If you want to set an expiration, just put a key in your data for access date and set it to new Date()
. Then, when you pull data, do a date check on the expiration key based on when it should expire.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With