@oyvindher/preserve
TypeScript icon, indicating that this package has built-in type declarations

0.3.1 • Public • Published

Preserve

A state lib for keeping track of and change localStorage data

Build Status PRs Welcome

Install

 npm install @oyvindher/preserve

or with Yarn

yarn add @oyvindher/preserve

API

preserve(key:string, initialData?: any)

The preserve function gives you 4 methods in return:

  • get<T>() Gives the current state of your localstorage item.
  • set<T>(data:T) Set the current state of your localstorage item.
  • subscribe(callback: (prevData, nextData) => void) Gives you a callback to listen to current state changes
  • clearItem() Clears the localStorge item

Basic usage

import preserve from '@oyvindher/preserve';

// Make an item you want to keep track of.
// The initial state is optional.
const myItem = preserve('myData', 0);
// Get the current data from localStorage key
myItem.get(); // 0
// Update the localStorage data.
myItem.set(1);
// Listen to changes that happens within your localStorage item
myItem.subscribe((prevData, nextData) => {
  console.log(prevData); // 0
  console.log(nextData); // 1
});
// Clear the item from localStorage
myItem.clearItem();

preserveLogger

PreserveLogger is a handy util for development for logging out previous and next state of any given preserved item when it changes.

This is how you would use it:

import preserve, { preserveLogger } from '@oyvindher/preserve';

const myItem = preserve('myItem');

// Pass the item you want to log.
preserveLogger(myItem);

Readme

Keywords

none

Package Sidebar

Install

npm i @oyvindher/preserve

Weekly Downloads

0

Version

0.3.1

License

MIT

Unpacked Size

8.12 kB

Total Files

18

Last publish

Collaborators

  • oyvindhermansen