forked from codeisneverodd/programmers-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorageEffect.ts
37 lines (33 loc) · 991 Bytes
/
storageEffect.ts
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
import { AtomEffect } from "recoil";
export function sessionStorageEffect<T>(key: string): AtomEffect<T> {
return ({ setSelf, onSet }) => {
if (typeof window === "undefined") return;
const savedValue = sessionStorage.getItem(key);
if (savedValue != null) {
setSelf(JSON.parse(savedValue));
}
onSet((newValue, _, isReset) => {
if (isReset) {
sessionStorage.removeItem(key);
} else {
sessionStorage.setItem(key, JSON.stringify(newValue));
}
});
};
}
export function localStorageEffect<T>(key: string): AtomEffect<T> {
return ({ setSelf, onSet }) => {
if (typeof window === "undefined") return;
const savedValue = localStorage.getItem(key);
if (savedValue != null) {
setSelf(JSON.parse(savedValue));
}
onSet((newValue, _, isReset) => {
if (isReset) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, JSON.stringify(newValue));
}
});
};
}