-
Notifications
You must be signed in to change notification settings - Fork 2
/
useAsyncStorage.ts
55 lines (48 loc) · 1.32 KB
/
useAsyncStorage.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
import { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
export default <T>(
key: string,
defaultValue?: T
): [T | null, (data: T) => T, () => void] => {
const [storageItem, setStorageItem] = useState<T>(null);
async function getStorageItem() {
try {
AsyncStorage.getItem(key, (e, data) => {
if (data !== null) {
setStorageItem(
JSON.parse(data, function (name, value) {
if (
typeof value === "string" &&
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(value)
) {
return new Date(value);
}
return value;
}) as T
);
} else {
setStorageItem(defaultValue);
}
});
} catch (error) {
setStorageItem(defaultValue ?? null);
}
}
function updateStorageItem(data: T) {
try {
AsyncStorage.setItem(key, JSON.stringify(data));
} catch (error) {
console.error("error saving data", error);
}
setStorageItem(data);
return data;
}
function clearStorageItem() {
AsyncStorage.removeItem(key);
setStorageItem(null);
}
useEffect(() => {
getStorageItem();
}, []);
return [storageItem, updateStorageItem, clearStorageItem];
};