timedstorage
v1.3.6
Published
Localstorage with expirations on data objects by key
Downloads
11
Maintainers
Readme
timedstorage
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
Table of Contents
Install
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
.
Usage
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');
}
Debug
Pop open the console and access your data directly and confirm it is correct.
console.log(window.localstorage.getItem('KEY_NAME'));
Examples
Interactive example on CodeSandbox.io - https://codesandbox.io/s/5vpn5828n
API
Table of Contents
deleteItem
Removes an object by key from localstorage
Parameters
key
string Key to remove
Examples
return deleteItem('KEY');
Returns undefined
getItem
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)
setItem
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
Reporting Issues
Found a problem? Want a new feature? Open a clear and descriptive issue.
License
MIT © Nicholas Smith