npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

var-persist

v1.0.1

Published

Sync variables with the local/session storage using proxy objects & decorators

Downloads

1,159

Readme

var-persist

TypeScript: Sync variables with localStorage

Version Pull Requests Issues



Table of Contents

About

Var-Persist is an updated version of webstorage-decorators, a library which saves variables to local or session storage.

This library aims to improve upon the original's limitations by using the new Proxy Object. Improvements include:

  • Supports both OOP & Decorator patterns
  • Proxy object ensures all changes are tracked including impure functions
  • [Proto]types and functions can be preserved by passing the type option

Disclaimer: JavaScript's decorators are currently undergoing changes to the API overseen by TC39 and currently have no support for property decorators. Experimental decorators must be enabled to work properly.

Examples

Using objects:

import {Persist} from 'var-persist';

// Proxy Object (Always access/modify using `.value`):
let theme = new Persist<string>('theme', {default: 'os'});

console.log(theme.value) // Output: os
theme.value = 'light'; // Changes will be synced to localStorage['theme'];

Using decorators:

import {persist} from 'var-persist';

// Using decorators
class Theme {
	@persist({key: 'theme', default: 'os'}) current!: string;
}
const theme = new Theme();

console.log(theme.current); // Output: light
theme.current = 'dark'; // You can ommit `.value` when using the decorator

Advanced uses:

import {Persist} from 'var-persist';

// Options are the same for both the persist decorator and object:
let example = new Persist<string[]>('example', {
	storage: SessionStorage, // Use a different storage solution
	default: [], // Default value if stored value === undefined
	type: Array // Ensures [proto]type & methods are restored
});

// Callback when changes are made
example.watch(value => console.log(`Length - ${value.length}`));
example.value = [1, 2, 3];
// Output: Length - 3
example.value.pop(); // Impure changes are saved
// Output: Length - 2

Built With

TypeScript

Setup

Prerequisites

Instructions

  1. Install persist: npm i var-persist
  2. Enable decorators inside tsconfig.json:
{
	"compilerOptions": {
		"experimentalDecorators": true,
		...
	},
	...
}
  1. Import & use, see examples above

Prerequisites

Instructions

  1. Install the dependencies: npm i
  2. Build library & docs: npm build
  3. Run unit tests: npm test

Documentation

Create a proxy object which wraps your data so any changes can be intercepted & synced with storage.

Your data is stored under the value property and should always be accessed/modified through it.

Example

import {Persist} from 'var-persist'

const theme = new Persist('theme.current', {default: 'os'});

console.log(theme.value); // Output: os
theme.value = 'light'; // Make sure you always use .value to access/modify data

location.reload(); // Simulate refresh
console.log(theme.value); // Output: light

Constructor

Persist<T>(key: string, options?: PersistOptions)

| Argument | Type | Description | |-----------|--------------------------------------------------|-------------------------------------------------------------| | key | string | Primary key value will be stored under | | options | PersistOptions<T> | Configure using PersistOptions |

Properties

| Name | Type | Description | |-----------|--------------------------------------------------|-------------------------------------------------------------| | key | string | Primary key value will be stored under | | options | PersistOptions<T> | Configure using PersistOptions | | value | T | Current value |

Methods

clear

Delete value from storage

clear(): void

load

Load value from storage

load(): void

save

Save current value to storage

save(): void

watch

Callback function which is run when there are changes

watch(fn: (value: T) => void): void

Parameters

| Name | Type | Description | |------|-------------------------|---------------------------------------------------------------------------------------| | fn | (value: T) => any | Callback will run on each change; it's passed the next value & it's return is ignored |

Returns

() => void - Function which will unsubscribe the watch/callback when called

toString

Return value as JSON string

toString(): string

Returns

string - Stringified JSON object

valueOf

Current value

valueOf(): T

Returns

T - Current value

Create a proxy object which wraps your data so any changes can be intercepted & synced with storage.

Your data is stored under the value property and should always be accessed/modified through it.

Example

import {Persist} from 'var-persist';

class Theme {
	// This property will automatically sync with localStorage
	@Persist({default: 'os'}) current!: string;

	constructor() {
		console.log(this.current); // Output: os
		this.current == localStorage.getItem('Thene.current'); // True
		this.current = 'light';
		console.log(this.current); // Output: light
	}
}

Constructor

persist(options?: {key?: string} & PersistOptions<T>)

| Argument | Type | Description | |-----------|--------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------| | options | {key: string} & PersistOptions<T> | Configure using PersistOptions. Storage key can also be ovverriden by passing key as an option |

PersistOptions<T>

Configurable options to change persistence behavior

| Property | Type | Description | |------------|-----------|----------------------------------------------------------------------------------------| | default? | T | Default/Initial value if undefined | | storage? | Storage | Storage implementation, defaults to LocalStorage. Can also be used with SessionStorage | | type? | any | Force value to have [proto]type |

License

Copyright © 2023 Zakary Timson | Available under MIT Licensing

See the license for more information.