-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
63 lines (56 loc) · 2.39 KB
/
index.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {StorageDescriptor, TStorageType} from "./index.types";
import React, {useEffect} from "react";
import { useAtom } from "jotai";
export const getFromPersistentStorage = <T> (storageType: TStorageType, key: string) => {
let storedValue : string | null;
switch(storageType){
case TStorageType.LocalStorage:
storedValue = localStorage.getItem(key);
break;
case TStorageType.SessionStorage:
storedValue = sessionStorage.getItem(key);
break;
default:
storedValue = null;
}
return storedValue !== null ? JSON.parse(storedValue) as T : undefined
}
const setToPersistentStorage = (storageType: TStorageType, key: string, value: string) => {
switch(storageType){
case TStorageType.LocalStorage:
localStorage.setItem(key, value);
break;
case TStorageType.SessionStorage:
sessionStorage.setItem(key, value);
break;
default:
break;
}
}
const removeFromPersistentStorage = (storageType: TStorageType, key: string) => {
switch(storageType){
case TStorageType.LocalStorage:
localStorage.removeItem(key);
break;
case TStorageType.SessionStorage:
sessionStorage.removeItem(key);
break;
default:
break;
}
}
export const usePersistentStorage = <T>(storageDescriptor: StorageDescriptor<T>) : [T, React.Dispatch<React.SetStateAction<T>>, () => void] => {
const {key, preferredStorage} = storageDescriptor;
const [value, setValue] = useAtom(storageDescriptor.getAtom());
useEffect(() => {
const initialValue = getFromPersistentStorage<T>(storageDescriptor.preferredStorage, storageDescriptor.key);
if (initialValue !== undefined) setValue(initialValue);
}, [key, preferredStorage, setValue]);
useEffect(() => {
if (value === null || value == undefined) removeFromPersistentStorage(storageDescriptor.preferredStorage, storageDescriptor.key);
else setToPersistentStorage(storageDescriptor.preferredStorage, storageDescriptor.key, JSON.stringify(value));
}, [key, preferredStorage, value]);
const removeValue = () => removeFromPersistentStorage(storageDescriptor.preferredStorage, storageDescriptor.key);
return [value, setValue, removeValue];
}
export {StorageDescriptor, TStorageType} from "./index.types";