Disclaimer: This is a very stable project with a very focused use-case. This project is actively used and maintained (as needed).
A tiny library for storing and expiring objects in localstorage.
- Small ~650b footprint
- Convenient Similar API to window.localStorage
- Useful Storage objects that expire in localstorage
This project uses node and npm.
npm install --save timedstorage
Then with a module bundler like webpack or another bundling solution:
import { deleteItem, getItem, setItem } from 'timedstorage';
The UMD build is also available. Pull the repo down locally and run npm run build
.
You'll find the library on window.timedstorage
.
import { deleteItem, getItem, setItem } from 'timedstorage';
// the time module gives helpful shortcuts for time in milliseconds
import * as time from 'timedstorage/time';
async function getUserData() {
// Retrieve the item from localstorage
let userData = getItem('user_key');
if (!userData) {
const response = await fetch('/user_endpoint');
// Set the item with your key
// `response` (the passed value to be saved) is expected to be an object
userData = setItem('user_key', response, time.HOUR);
}
return userData;
}
function deleteUserData() {
// Delete the item by key
return deleteItem('user_key');
}
Pop open the console and access your data directly and confirm it is correct.
console.log(window.localstorage.getItem('KEY_NAME'));
Interactive example on CodeSandbox.io - https://codesandbox.io/s/5vpn5828n
Removes an object by key from localstorage
Parameters
key
string Key to remove
Examples
return deleteItem('KEY');
Returns undefined
Get an item from localstorage by key. If it's expired or there is issue with any part of the data object, delete the item and return null.
Parameters
key
string Key to remove
Examples
return getItem('KEY');
Returns (null | Object)
Set an object into localstorage by key. Requires value to be an object. Expected expiration to be an int of milliseconds
Parameters
key
Int Length of time in millisecondsvalue
Object Object value to saveexpiration
Examples
return setItem('KEY', { data: 'wow' }, time.HOUR)
Returns Object
Found a problem? Want a new feature? Open a clear and descriptive issue.
MIT © Nicholas Smith