Simple Browser Local storage (and Session Storage) Abstraction.
Helps you work with browser localStorage (and sessionStorage) as a regular JavaScript object. It does this by allowing you use regular javascript object syntax.
To use it just install from npm with the following command:
npm install persisty
When working with localStorage
, you should import it as default like below:
// import persisty
import persisty from 'persisty';
or as a named import:
import { persistLocal } from 'persisty';
Note
You have the flexibility to use either the import of persisty
or persistLocal
, as they refer to the same functionality.
const orders = [
{ id: 1, quantity: 2 },
{ id: 2, quantity: 1 },
];
persisty.orders = orders // Also saved in you browser localStorage
// or use persistLocal from named import:
persistLocal.orders = orders
console.log(persisty.orders);
// Output:
// [
// { id: 1, quantity: 2 },
// { id: 2, quantity: 1 },
// ];
delete persisty.orders
console.log(persisty.orders); // null
Import persistSession
to interact with sessionStorage
.
// import persisty
import { persistSession } from 'persisty';
const orders = [
{ id: 1, quantity: 2 },
{ id: 2, quantity: 1 },
];
persistSession.orders = orders // Also saved in you browser sessionStorage
console.log(persistSession.orders);
// Output:
// [
// { id: 1, quantity: 2 },
// { id: 2, quantity: 1 },
// ];
delete persistSession.orders
console.log(persisty.orders); // null
Note
persisty does not support deep mutation (yet).
For example:
console.log(persisty.orders[0]) // { id: 1, quantity: 2 }
persisty.orders[0].id = 123
console.log(persisty.orders[0]) // { id: 1, quantity: 2 }
Won't work.
Issues/Feature request and PRs are welcome.
MIT License