2

I am using localStorage in my application. I want to clear those values after 20 minutes. Can u please help me out?

Janani
  • 21
  • 1
  • 1
  • 3

4 Answers4

6

I wrote an extension for angular-localStorage (https://github.com/grevory/angular-local-storage) that is able to delete entries in localStorage automatically when you provide an optional parameter in the set method.

https://gist.github.com/Kyoss79/8cd37a54679804fdeb6d

Kyoss
  • 172
  • 1
  • 11
  • 1
    Works great thanks! Should be part of the library. Maybe you could contribute? – Elger Mensonides Oct 19 '15 at 13:10
  • @Kyoss Am i right in thinking this adds an expiry time so you can query localstorage and remove the row if it's too old? I can't see anything that expires the row automatically? Neat addition. Would defintiely be worth having in the core lib. :) – JsAndDotNet Mar 03 '16 at 14:54
2

after bootstraping your module call run and setup an $interval that clears local storage after 20 minutes.

app.run(function($interval){
  $interval(() => {
    delete localStorage[key]
    // delete all the required localStorage variables by specifying their keys
  }, 1000*60*20)
})
  • @HarryBosh yes. The page would need to be open for this to work. We would have to store the data along with an expiry timestamp to validate it otherwise. This timestamp can be used while fetching the data and the function being used for this can delete the data and return null if it has expired. Hope this helps :) – Anil Dukkipatty Aug 13 '18 at 06:16
  • you cant really 'auto expire' if the page needs to be open – Harry Bosh Aug 14 '18 at 22:28
  • @HarryBosh that's correct you can't auto expire directly. You can use the workaround mentioned in the above comment. – Anil Dukkipatty Aug 20 '18 at 07:13
1

According to W3Schools:

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

However, a similar question has already been asked and answered elsewhere: When do items in HTML5 local storage expire? There were some workarounds mentioned there that may be of use to you.

Community
  • 1
  • 1
NoahC
  • 121
  • 5
0

You can have a custom generic implementation in one cache service or local storage service. Here is what worked for me.

import { Injectable } from '@angular/core';
// using ionic angular storage
import { Storage } from '@ionic/storage-angular'; 

export class CachedItem<T> {
  public _value: T | undefined;
  public _expiry: any;

  constructor(private name: string) { }

  public setValue(value: T) {
    this._value = value;
    this._expiry = new Date().getTime() + 1800000; // 30 mins 
  }
}

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
  }

  async init() {
    const storage = await this.storage.create();
    this._storage = storage;
  }
 
  private async CheckStorage() {
    if (!this._storage) {
      this._storage = await this.storage.create();
    }
  } 

  // Generic cache with expiry 
  public async setCache<T>(key: string, items: T) {
    let cachedItem = new CachedItem<T>(key);
    cachedItem.setValue(items);

    await this.CheckStorage();
    return await this._storage?.set(key, cachedItem);
  }

  public async getCache<T>(key: string) {
    await this.CheckStorage();
    const cashedItem: CachedItem<T> = await this._storage?.get(key);
    if (cashedItem !== null) {
      if (new Date().getTime() > cashedItem._expiry) {
        // If the item is expired, delete the item from storage  and return null
        await this._storage?.remove(key);
        return null
      }
      return cashedItem._value as T;
    }

    return null;
  }

}

You can use it like the one below

async loadData() {

    // gets the cache
    var datas: MyDataType[] = await this.localStorageService.getCache('datacachekey');
    if (datas == null) { // not available in the cache, go fetch and put into the cache
      
      this.myDataService.getDatasFromApi().subscribe(
        (myData) => {
          // sets the cache
          await this.localStorageService.setCache('datacachekey', myData); 

          // work on the data 
        },
        () => {
          //error;
        }
      );

    }
    else {
       // work on the data as received from cache
    }
  }
Mahendra
  • 447
  • 6
  • 7