tsironis / lockr Goto Github PK
View Code? Open in Web Editor NEWA minimal API wrapper for localStorage
License: MIT License
A minimal API wrapper for localStorage
License: MIT License
Should we need this ? Willing to do a pull.
Examples in the specs are tightly coupled between them and also they must run in a predefined sequence, which makes them harder to read, follow and write.
We should find an elegant way to flush localStorage before each example and a way to support factories.
Let's stay with official examples:
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]);
and after Lockr.get('users'); it give me sting (JSON)?
But how can I make an "each" loop to get all key/value?
Something like this but this give me en error
$.each(Lockr.get('selects'), function (index, value) { console.log(value); });
I added my product into shopping cart by using:
Lockr.sadd("cart", {id: 123, name: abc});
Lockr.sadd("cart", {id: 456, name: def});
How to remove a particular object from cart? e.g I later want to remove the first object {id: 123, name: abc}
thanks
I tried a simple sadd example:
Lockr.sadd("testS", 1);
And I get this in console:
Uncaught TypeError: values.indexOf is not a function
I'd like to use lockr for a new component, but with sessionStorage instead of localStorage.
As far as I can see lockr is built for localStorage only.
Would it be possible to provide sessionStorage support as well or is this plugin intentionally restricted to localStorage?
When I try to do Lockr.get('obj');
and obj holds an array of objects, I jut get [object object]
and not the actual value of these objects. When I use JSON.stringify(obj)
I get the values.
This is not what I expected after reading the documentation of Lockr.
I've set a localStorage item:
Lockr.set('item', 'itemValue')
Now I want to remove this item, is there an api like:
Lockr.remove('item')
thank you.
I have here a very simple code which is roughly like this:
object.somedata: {
'a': Lockr.get('a'),
'b': Lockr.get('b'),
'c': Lockr.get('c')
}
At the row "c" I get now the error message "TypeError: Lockr.get(...) is undefined" in the console of Firefox. Any idea why?
Hello.Consider the following foo
object with a name
property and a greet
function:
var foo = {name:"foo",greet:function(){console.log("Hello:"+this.name)}
Now we store it:
Lockr.set("test",foo)
Let's try to restore it :
var restored = Lockr.get("test")
If we try to do restored.greet()
we get an error saying restored.greet is not a function
.
Why is this happening?
Lockr.sismember = function(key, value, options) {
-----> var query_key = this._getPrefixedKey(key, options); <----
return Lockr.smembers(key).indexOf(value) > -1;
};
Please, remove it, if it is not required.
Please add append functionality.
ex:-
Lockr.append( key, value);
check first key exist in storage. if not then create new on. if exist then append in existing value.
Please add getLastKey and getFirstKey;
Lockr.getLast = function(){
return Object.keys(localStorage)[Object.keys(localStorage).length - 1];
}
Lockr.getFirst = function(){
return Object.keys(localStorage)[0];
}
Web developers will be need first, last key ot findKey function for find something.
https://github.com/tsironis/lockr/blob/master/lockr.js#L18
Need to check for the exception: QUOTA_EXCEEDED_ERR
How to find index of Array Lockr
Let's say we do the following to store a name in localStorage using Lockr:
Lockr.set("name","foo");
Now let's add an item to the localStorage without using Lockr
"
localStorage.setItem("fakeName","just a fake name");
As you can see fakeName
item was added to localStorage without using Lockr.
So now comes the question.
Should Lockr clear all the localStorage when .flush()
is called or only the items added by Lockr?
getAll()
returns only the prefixed keys, shouldn't flush()
remove only those as well?
Hi,
I think the Lockr.rm method should look like this to correctly handle usage with prefix
Lockr.rm = function (key, options) {
localStorage.removeItem(this._getPrefixedKey(key, options));
}
As far as I can see #34 can be closed
Hi,
Thank you for writing this library. Its very helpful in my project.
Can you give some information on the difference between get
and getItem
. I'm asking because, for some reason, getItem
is not working for me (Lockr.getItem(...) - getItem() is not a function
)).
Regards,
Akash
Hello.I have been trying to save the following to localStorage
:
var a = new Set(); a.add(1); a.add(2);
Lockr.set('demo',a);
However if I do this :Lockr.get("demo")
I get an empty object,Any ideas?
Recently switching my projects to es6 with babel, I'd like to do something like this with lockr:
import {
get,
set,
} from 'lockr'
but when I call get
this error throws:
TypeError: Cannot read property '_getPrefixedKey' of undefined
var query_key = this._getPrefixedKey(key, options)
Not a big deal; importing the entire library is not a problem because it's small and minimal.
Thank you =]
I've come across a situation where I need to use Lockr
in two different places with different prefixes. But Locker.prefix = 'new_prefix_'
will just override the old one. Is this possible at all?
Thanks for this amazing library!
Thanks for this super tiny package that elegantly handles the localStorage ๐
I can see that Lockr
is not designed to retrieve data that are not set by itself. Can we make it to retreive the data that are not set by Lockr
with the help of options argument ?
like,
window.localStorage.setItem('nameObj', JSON.stringify({first: 'Gokul', last: 'Kathirvel'}));
Lockr.get('nameObj');
// undefined
Lockr.get('nameObj', null, { processRaw: true });
// {first: 'Gokul', last: 'Kathirvel'}
or if the fetched value from storage is not abiding the structure (.data
), then we can return the actual fetched value itself like this
Lockr.set("xyz", false); console.log(Lockr.get("xyz"));
the following prints "undefined" instead of the expected "false". looking at your code the problems seems to be somewhere here: https://github.com/tsironis/lockr/blob/master/lockr.js#L81 - your minifier changes that line to return null===value?missing:value.data||missing
(https://github.com/tsironis/lockr/blob/master/lockr.min.js), which is a lot cleaner in my opinion and also quite obviously displays the problem at hand.
is this behavior by design?
thank you first
now i used Vue but when i import it doest work well
so
Suggest UMD method to pack
Hi, Happy to see the new version!
Could you add the dist/
folder to an NPM package, or add a prepare
npm script?
Hello,
First of all, great package for maintaining Local storage. The thing which i have to ask here that how can i set a time/days to expire/clear local storage because i need to expire my shopping cart after 30 days or less if there is no working on it. Right now, i think there is no way to expire.
Thank you for any help.
The link for manual download in the README.md leads to a subdomain, which is deprecated in github pages.
I think it's time to start planning our v1.0 release and a basic roadmap of how to get there.
I would like to get the discussion started on how we can improve this library. Any suggestions will be much appreciated.
If any of my values in localStorage are non-valid json, I get the following error when calling Lockr.getAll()
Shouldn't we return missing;
here ?
Hi, so I am trying to utilize Lockr to enable a more advanced data storage system within my website. The problem is I'm not sure how to access the data once I've stored it in a more advanced way using Lockr. My code is below. I'm talking about specifically writing the data in a paragraph within the updateAllDataDisplay function when the page loads. I can get the data logged to the console, but I can't seem to manipulate it properly beyond that. My goal is to have the website display the entry date, entry time, exercise entry, food entry, and mood entry, in that order on the page. Any help? Thanks
// Script
// Goals: Be able to store data with the date, and a journal entry
// Create dynamic showing of entries
// Be able to have multiple entries for one date in order
// Add food entries
// Add exercise entries
// Add weight entry add weight graph
// Add calorie entry
// Add mood entries for each date
// Add streak showings for entries
// Add calandar functionality
//
(function(root, factory) {
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = factory(root, exports);
}
} else if (typeof define === 'function' && define.amd) {
define(['exports'], function(exports) {
root.Lockr = factory(root, exports);
});
} else {
root.Lockr = factory(root, {});
}
}(this, function(root, Lockr) {
'use strict';
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Lockr.prefix = "";
Lockr._getPrefixedKey = function(key, options) {
options = options || {};
if (options.noPrefix) {
return key;
} else {
return this.prefix + key;
}
};
Lockr.set = function (key, value, options) {
var query_key = this._getPrefixedKey(key, options);
try {
localStorage.setItem(query_key, JSON.stringify({"data": value}));
} catch (e) {
if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
}
};
Lockr.get = function (key, missing, options) {
var query_key = this._getPrefixedKey(key, options),
value;
try {
value = JSON.parse(localStorage.getItem(query_key));
} catch (e) {
if(localStorage[query_key]) {
value = {data: localStorage.getItem(query_key)};
} else{
value = null;
}
}
if(!value) {
return missing;
}
else if (typeof value === 'object' && typeof value.data !== 'undefined') {
return value.data;
}
};
Lockr.sadd = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options),
json;
var values = Lockr.smembers(key);
if (values.indexOf(value) > -1) {
return null;
}
try {
values.push(value);
json = JSON.stringify({"data": values});
localStorage.setItem(query_key, json);
} catch (e) {
console.log(e);
if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
}
};
Lockr.smembers = function(key, options) {
var query_key = this._getPrefixedKey(key, options),
value;
try {
value = JSON.parse(localStorage.getItem(query_key));
} catch (e) {
value = null;
}
return (value && value.data) ? value.data : [];
};
Lockr.sismember = function(key, value, options) {
return Lockr.smembers(key).indexOf(value) > -1;
};
Lockr.keys = function() {
var keys = [];
var allKeys = Object.keys(localStorage);
if (Lockr.prefix.length === 0) {
return allKeys;
}
allKeys.forEach(function (key) {
if (key.indexOf(Lockr.prefix) !== -1) {
keys.push(key.replace(Lockr.prefix, ''));
}
});
return keys;
};
Lockr.getAll = function (includeKeys) {
var keys = Lockr.keys();
if (includeKeys) {
return keys.reduce(function (accum, key) {
var tempObj = {};
tempObj[key] = Lockr.get(key);
accum.push(tempObj);
return accum;
}, []);
}
return keys.map(function (key) {
return Lockr.get(key);
});
};
Lockr.srem = function(key, value, options) {
var query_key = this._getPrefixedKey(key, options),
json,
index;
var values = Lockr.smembers(key, value);
index = values.indexOf(value);
if (index > -1)
values.splice(index, 1);
json = JSON.stringify({"data": values});
try {
localStorage.setItem(query_key, json);
} catch (e) {
if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
}
};
Lockr.rm = function (key) {
var queryKey = this._getPrefixedKey(key);
localStorage.removeItem(queryKey);
};
Lockr.flush = function () {
if (Lockr.prefix.length) {
Lockr.keys().forEach(function(key) {
localStorage.removeItem(Lockr._getPrefixedKey(key));
});
} else {
localStorage.clear();
}
};
return Lockr;
}));
//localStorage.removeItem('allData');
var allData = [];
init();
function init() {
/*
if (Lockr.get('allData') !== null && Lockr.get('allData') !== undefined) {
allData = JSON.parse(Lockr.get("allData"));
dataEntries = Lockr.get('dataEntries');
//console.log(allData);
} else {
//console.log('blank exercise data array');
allData = [];
dataEntries = 0;
}
*/
if (Lockr.get('dataEntries') > 0) {
dataEntries = Lockr.get('dataEntries');
}
}
// Create exercise field
let a = document.createElement("input");
a.setAttribute("type", "text");
a.setAttribute("value", "How long did you exercise for today");
a.size = "40";
document.body.appendChild(a);
// Create two <br> between text fields
for (let i = 0; i < 2; i ++) {
let d = document.createElement('br');
document.body.appendChild(d);
}
// Create diet text field
let e = document.createElement("input");
e.setAttribute("type", "text");
e.setAttribute("value", "What did you eat today");
e.size = "40";
document.body.appendChild(e);
// Create two <br> between text fields
for (let i = 0; i < 2; i ++) {
let d = document.createElement('br');
document.body.appendChild(d);
}
let f = document.createElement("input");
f.setAttribute("type", "text");
f.setAttribute("value", "Describe your mood in detail today");
f.size = "40";
document.body.appendChild(f);
for (let i = 0; i < 2; i ++) {
let d = document.createElement('br');
document.body.appendChild(d);
}
// Create save data button
let saveDataBtn = document.createElement("button");
saveDataBtn.innerHTML = "Save Data";
document.body.appendChild(saveDataBtn);
for (let i = 0; i < 3; i ++) {
let d = document.createElement('br');
document.body.appendChild(d);
}
// Create clear data button
let clearDataBtn = document.createElement("button");
clearDataBtn.innerHTML = "Clear Data";
document.body.appendChild(clearDataBtn);
// Create allData Header
let b = document.createElement("p");
let c = document.createTextNode('Saved Data:');
b.appendChild(c);
document.body.appendChild(b);
(function updateAllDataDisplay() {
for (var i = 0; i < dataEntries; i++) {
let currentEntry = Lockr.get(`data${i}`);
console.log(currentEntry);
let a = document.createElement("p");
let b = document.createTextNode('blah');
a.appendChild(b);
document.body.appendChild(a);
}
})();
/*
Goal: create buttons that toggle between showing a user inputted pragraph tracking their moood on the day they exercised for x number of inputted hours
*/
saveDataBtn.onclick = function () {
var date = new Date();
let day = date.getDate();
let month = date.getMonth();
let year = date.getFullYear();
let hours = date.getHours();
let mins = date.getMinutes();
let secs = date.getSeconds();
//allData.push(`${day}/${month + 1}/${year} (${hours}:${mins}:${secs}): ${a.value}. ${e.value}. ${f.value}.`);
//localStorage.setItem("allData", JSON.stringify(allData));
//Lockr.set('allData', JSON.stringify(allData));
//Lockr.set('newData', [{first: `${a.value}`}, {second: `${e.value}`}, {third: `${f.value}`}]);
//console.log(Lockr.get('newData'));
dataEntries += 1;
Lockr.set(`data${dataEntries}`, [{date:`${day}/${month + 1}/${year}`, time: `${hours}:${mins}:${secs}`, exerciseHours: a.value, food: e.value, mood: f.value}, {test: 'testing'}]);
Lockr.set('dataEntries', dataEntries);
console.log(Lockr.get(`data${dataEntries}`));
console.log(dataEntries);
}
clearDataBtn.onclick = function () {
//localStorage.removeItem('allData');
for (var i = 0; i < dataEntries; i++) {
Lockr.rm(`data${i}`);
}
dataEntries = 0;
//Lockr.rm('');
}
Basic usage is causing a reference error. Thoughts?
Lockr.prefix = 'lockr';
Lockr.set('website', 'website.com');
Lockr.set('categories', 8);
Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);
This code will not work.
You use prefix without underscore at the end. But in method getItem you use [prefix]_[key]. But underscore is never added to key, so correct would be localStorage.getItem('lockrusername');
Lockr.prefix = 'lockr';
Lockr.set('username', 'Coyote'); // Saved as string
localStorage.getItem('username');
> null
localStorage.getItem('lockr_username');
> {"data":123}
And you set username as string, but returned is number
I'm using locker to manage a very large list of users.
I wonder how you do to perform a search.
Example result I expect
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]); Lockr.getWhere('users', {age = 18}]); // return {name: 'John Doe', age: 18}
Thanks
I'm sorry, my English is not good.
Function wrapper localStorage.removeItem?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.