Skip to content

Commit deb0b67

Browse files
committed
feat: local storage helper
1 parent c563b01 commit deb0b67

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
export const hasLocalStorage = (): boolean => {
2+
return typeof localStorage !== 'undefined';
3+
};
4+
5+
export const LocalStorage = {
6+
/**
7+
* Gets a JSON value from local storage for the given key.
8+
* If either local storage isn't defined or key not found then
9+
* returns undefined.
10+
*/
11+
get: <T>(key: string): T | undefined => {
12+
if (!hasLocalStorage()) {
13+
return;
14+
}
15+
const value = localStorage.getItem(key);
16+
if (value) {
17+
return JSON.parse(value);
18+
}
19+
return;
20+
},
21+
/**
22+
* Sets a JSON value in local storage for the given key.
23+
* The value should be JSON serializable.
24+
* For example, not a `Map` or `Set` because those become `{}`.
25+
*/
26+
set: <T>(key: string, value: T): void => {
27+
if (!hasLocalStorage()) {
28+
return;
29+
}
30+
localStorage.setItem(key, JSON.stringify(value));
31+
},
32+
};

0 commit comments

Comments
 (0)