localStorage is one of the options an application has if it needs to store data on the client-side. It is a key/value store and provides a straightforward API. All modern browsers support it (IE since version 8).
localStorage ¶
setItem
stores a value with a certain key. The first argument is the name of the key, and the second argument is the value. A key can only exist once. Calling setItem
multiple times with the same key overwrites the previous entry. Key and value must be a string, setItem
automatically converts a non-string value to a string. This is a problem for objects because they get converted to the string "[object Object]"
. To solve that, an application has to convert objects to a string before it calls setItem. One way to do it is with the JSON.stringify
function.
localStorage.setItem('one', '1');
localStorage.setItem('two', 2); // automatically converts 2 to the string "2"
const myObj = {firstName: 'John', lastName: 'Doe', age: 36};
localStorage.setItem('123', JSON.stringify(myObj));
getItem
retrieves the value for a specific key. The function returns null when the key does not exists.
const a = localStorage.getItem('one'); // "1"
const b = localStorage.getItem('two'); // "2"
const obj = JSON.parse(localStorage.getItem('123')); // {firstName: 'John', lastName: 'Doe', age: 36}
Another possibility to set and get values is by directly accessing the key like a property on the localStorage object.
localStorage.one = '1'; // same as localStorage.setItem('one', '1');
const c = localStorage.one; // same as const c = localStorage.getItem('one');
It's possible to mix both approaches.
localStorage.two = '2'
const t = localStorage.getItem('two'); // "2"
There is one subtle difference in the behaviour when the key does not exist. getItem
returns null and the property access returns undefined
const x = localStorage.getItem('xyz'); // null
const y = localStorage.xyz; // undefined
When the key is not a valid name for a property the application needs to use the ['property']
syntax (or setItem and getItem).
localStorage['11'] = 'eleven';
const e = localStorage['11']; // "eleven"
removeItem
removes the entry for a specific key.
localStorage.removeItem('one');
clear
removes all key/value pairs.
localStorage.clear();
Another related storage option is sessionStorage
. It provides the same functions as localStorage. The big difference is that data stored in localStorage survives a browser restart, data in sessionStorage does not. But even the data survives a browser restart; an application should not depend on the prospect that the data is stored and available forever. The data in a localStorage can be erased at any time either by the user or browser. iOS, for example, removes data from the localStorage when it runs low on storage.
Lockr ¶
In the examples above, we saw that keys and values need to be strings. When the application stores a number, localStorage automatically converts it to a string and getItem
returns a string. An application can solve that by converting the value with JSON.stringify
and JSON.parse
.
Lockr is a thin wrapper around localStorage. This library does the conversion to JSON behind the scenes and makes your application's code more concise. This example stores a number and a boolean and returns the values with the same type.
Lockr.set('four', 4);
Lockr.set('five', true);
const f = Lockr.get('four'); // 4
const v = Lockr.get('five'); // true
Lockr has a size of 3000 bytes (version 0.8.4) in minified form and can be installed with bower, npm, or with a simple script tag in the HTML page. In an npm project, you can install it with the following command
npm install lockr
And if you work with TypeScript you can install the TypeScript definition file like this:
npm install @types/lockr --save-dev
set
and get
support storing and retrieving objects.
Lockr.set('anObject', {firstName: 'John', lastName: 'Doe', age: 36});
const anObject = Lockr.get('anObject'); // {age:36, firstName:"John", lastName:"Doe"}
The get
function supports an optional second argument that specifies a default value that is returned when the key does not exist.
const s = Lockr.get('six', 0); // 0
The rm
function removes a key/value entry.
Lockr.rm('four');
Lockr.flush()
removes everything in the localStorage. It also deletes key/value entries that are stored directly with the localStorage
object.
Lockr does not only wrap existing localStorage function; it also adds some useful functionality on top of localStorage.
getAll()
returns an array with all the stored values.
Lockr.set('1', 'one');
Lockr.set('2', 2);
Lockr.set('3', {name:'John', age: 36});
const values = Lockr.getAll(); // ["one", 2, {age:36,name:"John"}]
The following functions are inspired by Redis and allow an application to manage a set like structure with a specific key.
sadd
adds a value to a set. If the application tries to add the same value multiple times sadd
ignores the call.
Lockr.sadd('bond', 'Daniel'); // ["Daniel"]
Lockr.sadd('bond', 'Sean'); // ["Daniel", "Sean"]
Lockr.sadd('bond', 'Daniel'); // ["Daniel", "Sean"]
smembers
returns the values of a set as an array.
Lockr.sadd('bond', 'Pierce');
Lockr.sadd('bond', 'Roger');
Lockr.smembers('bond'); // ["Pierce", "Roger"]
sismember
returns true when the value exists in the set otherwise false.
Lockr.sadd('bond', 'Daniel');
Lockr.sadd('bond', 'Roger');
Lockr.sismember('bond', 'Daniel'); // true
Lockr.sismember('bond', 'Jack'); // false
srem
removes a value from a set.
Lockr.sadd('bond', 'Pierce');
Lockr.sadd('bond', 'Jack');
Lockr.srem('bond', 'Jack');
Lockr.smembers('bond'); // ["Pierce"]