A handy wrapper around localStorage.
- What you see is what you get; Simple and clean wrapper, nothing extra
- Respects types; no longer do you have to worry about casting items after retrieving them
- Custom events on actions; listen to events on
set
,remove
, andclear
Note: This wrapper will not work if the localStorage
API is not available.
npm i @script47/local-storage
<script src="https://unpkg.com/@script47/local-storage"></script>
ls(key, value);
ls('key', 'value'); // true
// or
ls({
key: 'value'
});
ls('key'); // 'value'
set(key, value);
ls.set('key', 'value'); // true
// or
ls.set({
key: 'value'
})
get(key, def = undefined);
ls.set('key', 'value'); // true
ls.set('key', 'default value'); // 'value'
ls.get('i-dont-exist', 'default value'); // 'default value'
ls.get('i-dont-exist'); // undefined
remove(key);
ls.set('key', 'value'); // true
ls.get('key'); // 'value'
ls.remove('key'); // true
// or
ls.remove(['key']);
ls.get('key'); // undefined
clear();
ls.set('key', 'value'); // true
ls.set('another-key', 'another-value'); // true
ls.clear(); // true
ls.get('key'); // undefined
ls.get('another-key'); // undefined
on(type, listener);
ls.on('ls.set', ({detail}) => {
console.log(`${detail.key}=${detail.value}`);
});
ls.on('ls.remove', ({detail}) => {
console.log(`${detail.key} was removed.`);
});
ls.on('ls.clear', () => {
console.log('localStorage was cleared.');
})
ls.set('name', 'John Doe');
ls.set('age', 35);
setTimeout(() => {
ls.remove('name');
setTimeout(() => {
ls.clear();
}, 2500);
}, 2500);