DEV Community

Cover image for Set an expiration tine React Native AsyncStorage
Pierre-Henry Soria ✨
Pierre-Henry Soria ✨

Posted on • Updated on

Set an expiration tine React Native AsyncStorage

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

By default, similar to localStorage on the Web, AsyncStorage is designed to only handle storage and nothing more. That's why there is no built-in 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 30min

const now = new Date();
now.setMinutes(now.getMinutes() + storageExpirationTimeInMinutes); // add the expiration time to the current Date time
const expiryTimeInTimestamp = Math.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)
);
Enter fullscreen mode Exit fullscreen mode

Then, 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 = Math.floor(Date.now() / 1000); // get current UNIX timestamp. Divide by 1000 to get seconds and round it down

// Remove the saved data if it expires.
// 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
}
Enter fullscreen mode Exit fullscreen mode

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 💡


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

Happy coding! 🤠

Top comments (3)

Collapse
 
pl profile image
Phil Lindsay • Edited

Works great - thanks for the tip! Just a minor point - there is a typo where it should be Math.floor instead of Match.floor ;-)

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Great catch @pl! 😊 I've fixed it now.

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Any questions, feel free to post them below. I will be happy to answer! 🙂