7 * Enhances the local storage capabilities by allowing data to be stored with an expiration time.
8 * When data expires, it can be automatically purged from storage.
10 const localStorageWithExpiry = {
12 * Stores a data item with an expiration time in local storage.
14 * @param key - The key under which the item will be stored.
15 * @param value - The stringified value to be stored.
16 * @param expirationInMs - The duration in milliseconds after which the item expires. Defaults to 600000ms (10 minutes).
18 storeData: (key: string, value: string, expirationInMs: number = 10 * 60 * 1000): void => {
19 const item: StoredItem = {
21 expiresAt: Date.now() + expirationInMs,
23 window.localStorage.setItem(key, JSON.stringify(item));
27 * Retrieves a data item from local storage if it has not expired.
29 * @param key - The key of the item to retrieve.
30 * @returns The stored value if it is still valid, or null if it has expired or does not exist.
32 getData: (key: string): string | null => {
33 const storedValue = window.localStorage.getItem(key);
35 const { value, expiresAt }: StoredItem = JSON.parse(storedValue);
36 if (expiresAt > Date.now()) {
39 window.localStorage.removeItem(key);
45 * Removes a data item from local storage.
47 * @param key - The key of the item to remove.
49 deleteData: (key: string): void => {
50 window.localStorage.removeItem(key);
54 * Checks if a data item in local storage has expired and removes it if so.
56 * @param key - The key of the item to check for expiration.
58 deleteDataIfExpired: (key: string): void => {
59 const storedValue = window.localStorage.getItem(key);
61 const { expiresAt }: StoredItem = JSON.parse(storedValue);
62 if (expiresAt < Date.now()) {
63 window.localStorage.removeItem(key);
69 export default localStorageWithExpiry;