How to set an expiration time React Native AsyncStorage?

How to set an expiration time React Native AsyncStorage?

Today, I will show you how to quickly set an expiration time/date with the React Native AsyncStorage.

By default, similar to localStorage on the Web, AsyncStorage is designed to only to handle storage and nothing more. That’s why there is no expiration time.

However, there are some use cases where it can be useful to have an expiry date.

To do so, you will need to store in a JSON object an expiration date along with the actual data you wish to store.

For instance, here is an example with an expiration time in minutes.

import AsyncStorage from '@react-native-async-storage/async-storage';

// …

const storageKeyName = "storageWithExpiry";
const storageExpirationTimeInMinutes = 30; // in this case, we only want to keep the data for 30 minutes

const now = new Date();
now.setMinutes(now.getMinutes() + storageExpirationTimeInMinutes); // add the expiration time to the current Date time
const expiryTimeInTimestamp = Match.floor(now.getTime() / 1000); // convert the expiry time in UNIX timestamp
const data = {
  itemId: 4325 // example of data you need to store
  expiryTime: expiryTimeInTimestamp
};

// store the data with expiration time in there
await AsyncStorage.setItem(
  storageKeyName,
  JSON.stringify(data)
);

Then, when we will retrieve the item from AsyncStorage, and clean it up if the expiration time has reached

import AsyncStorage from '@react-native-async-storage/async-storage';

// …

let savedData = async AsyncStorage.getItem(
  storageKeyName
);
if (savedData !== null) { 
  // check if we got a valid data before calling JSON.parse
  savedData = JSON.parse(savedData);
}

const currentTimestamp = Match.floor(Date.now() / 1000); // get current UNIX timestamp. Divide by 1000 to get seconds and round it down

// Remove the saved data if it got expired.
// Check if expiryTime exists with the optional chaining operator ?
// then, we check if the current ‘now’ time is still behind expiryTime
// if not, it means the storage data has expired and needs to be removed
if (currentTimestamp >= savedData?.expiryTime) {
  async AsyncStorage.removeItem(storageKeyName);

  return; // if needed, you can leave the function here depending of your function’s logic
}

Note: To keep the examples clear and small, I have purposely omitted the try/catch blocks. However, when dealing with AsyncStorage, you would need to handle and catch the potential thrown errors.

Feel free to comment below if you have questions 💡

Happy coding! 🤠


🤖 Side-Projects on GitHub: GitHub.com/pH-7