forked from null-none/react-localstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-localstorage.js
36 lines (33 loc) · 1.03 KB
/
react-localstorage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
exports.reactLocalStorage = {
set: function(key, value) {
localStorage[key] = value;
return localStorage[key];
},
get: function(key, defaultValue=undefined, silent=true) {
var value = localStorage.hasOwnProperty(key) ? localStorage[key] : defaultValue;
// if silent=false throw error
if(!silent && !value)
throw key + " not found in localStorage";
return value;
},
setObject: function(key, value) {
localStorage[key] = JSON.stringify(value);
return localStorage[key];
},
getObject: function(key, defaultValue={}, silent=true) {
value = this.get(key, JSON.stringify(defaultValue), silent);
try{
return JSON.parse(value);
} catch(e) {
// will raise error for parsing
if(!silent)
throw 'Error in parsing value'
}
},
clear: function() {
return localStorage.clear();
},
remove: function(key) {
return localStorage.removeItem(key);
},
}