npm.io
1.2.5 • Published 4 years ago

local-storage-helper

Licence
MIT
Version
1.2.5
Deps
1
Size
12 kB
Vulns
0
Weekly
0
Stars
2

Local Storage Helper

It helps you to work with LocalStorage

npm version GitHub issues GitHub stars GitHub license

Usage

Step 1: Install local-storage-helper

npm install local-storage-helper --save

Step 2: Set up application prefix

import { LocalStorageHelper } from 'local-storage-helper';

LocalStorageHelper.setAppPrefix('yourPrefix');

Step 3: Start using

   const account = new LocalStorageHelper('account');
   account.save(someData);

Methods

Method Type Description
save (new (options: any) => T | any) => void This method save data to LocalStorage
restoreAs (Type?: new (options: any) => T) => T | any This method get data from LocalStorage, and can automatically convert to Class instance

Static Methods

Method Type Description
setAppPrefix (value: string) => void This method will set a prefix to your keys in LocalStorage

Example with RxJs


class Account {
    ...
}

class AccountService {
  private readonly subAccount: BehaviorSubject<Account>;
  private readonly accountStorage: LocalStorageHelper<Account> = new LocalStorageHelper<Account>('account');

  constructor() {
    this.subAccount = new BehaviorSubject(this.accountStorage.restoreAs(Account));
    this.subAccount.subscribe((account => this.accountStorage.save(account)));
  }

  public get account(): Account {
    return this.subAccount.getValue();
  }

  public set account(value: Account) {
    this.subAccount.next(value);
  }

  public clear(): void {
    this.account = null;
  }
}

License

MIT

Keywords