-
Notifications
You must be signed in to change notification settings - Fork 527
Expand file tree
/
Copy pathlocal-storage.js
More file actions
38 lines (35 loc) · 936 Bytes
/
local-storage.js
File metadata and controls
38 lines (35 loc) · 936 Bytes
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
37
38
/**
* Reads setting from the `localStorage` with a given `id` as JSON. If JSON
* parse is failed setting is interpreted as a string value.
* @param {string} id
* @returns {string|object|null}
*/
export const readSetting = (id) => {
/** @type {string|null} */
let setting = null
if (window.localStorage) {
try {
setting = window.localStorage.getItem(id)
} catch (error) {
console.error(`Error reading '${id}' value from localStorage`, error)
}
try {
return JSON.parse(setting || '')
} catch (_) {
// res was probably a string, so pass it on.
return setting
}
}
return setting
}
/**
* @param {string} id
* @param {string|number|boolean|object} value
*/
export const writeSetting = (id, value) => {
try {
window.localStorage.setItem(id, JSON.stringify(value))
} catch (error) {
console.error(`Error writing '${id}' value to localStorage`, error)
}
}