2021-01-28 13:15:46 -05:00
|
|
|
# WebStorage Decorators
|
|
|
|
A Javascript library that adds property decorators to sync a class property with the local or session storage.
|
2019-05-09 14:26:06 -04:00
|
|
|
|
2021-01-28 13:15:46 -05:00
|
|
|
## Quick Setup
|
|
|
|
1. Install with: `npm install --save webstorage-decorators`
|
|
|
|
2. Add the decorator to your property and use as normal!
|
|
|
|
```typescript
|
|
|
|
import {LocalStorage, SessionStorage} from 'webstorage-decorators';
|
2019-05-09 14:26:06 -04:00
|
|
|
|
2021-01-28 13:15:46 -05:00
|
|
|
export class MyCustomClass {
|
|
|
|
@LocalStorage({key: 'site_theme', default: 'light_theme'}) theme: string;
|
|
|
|
@SessionStorage({encryptWith: config.entryptionKey}) thisUser: User;
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
console.log(this.theme, localStorage.getItem('theme')); // Output: 'light_theme', 'light_theme'
|
|
|
|
console.log(this.user, localStorage.getItem('user')); // Output: null, undefined
|
|
|
|
user = {first: 'John', last: 'Smith', ...}
|
|
|
|
console.log(this.user, this.user == localStorage.getItem('user')); // Output: {first: 'John', last: 'Smith', ...}, true
|
|
|
|
}
|
|
|
|
}
|
2019-05-09 14:26:06 -04:00
|
|
|
```
|
2021-01-28 13:15:46 -05:00
|
|
|
|
|
|
|
## Caveats
|
|
|
|
Impure functions don't use the Object's setter preventing the storage from being updated. To prevent this use a pure
|
|
|
|
function or save it manually by reading the variable. (Reading triggers change detection & save if there are differences)
|
|
|
|
```typescript
|
|
|
|
@LocalStorage([1, 2]) example: number[];
|
|
|
|
example.push(3) // Impure & won't update storage
|
|
|
|
console.log(localStorage.getItem('example')) // Output: [1, 2];
|
|
|
|
example; // Trigger save
|
|
|
|
console.log(localStorage.getItem('example')) // Output: [1, 2, 3];
|
|
|
|
|
|
|
|
// OR
|
|
|
|
|
|
|
|
example = example.concat([3]); // Pure function requires you to use the setter triggering automatic saving
|
|
|
|
```
|