-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathuseAsyncStorage.ts
More file actions
44 lines (39 loc) · 2.27 KB
/
useAsyncStorage.ts
File metadata and controls
44 lines (39 loc) · 2.27 KB
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
import { useState, useEffect, useCallback } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
function useAsyncStorage<T>(
key: string,
defaultValue: T
): [T, (value: T) => Promise<void>, boolean] {
const [value, setValue] = useState<T>(defaultValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadValue = async () => {
try {
const stored = await AsyncStorage.getItem(key);
if (stored !== null) {
setValue(JSON.parse(stored));
} else {
setValue(defaultValue);
}
} catch (error) {
setValue(defaultValue);
} finally {
setLoading(false);
}
};
loadValue();
}, [key]);
const setStoredValue = useCallback(
async (newValue: T) => {
try {
await AsyncStorage.setItem(key, JSON.stringify(newValue));
setValue(newValue);
} catch (error) {
console.error('Error saving to AsyncStorage:', error);
}
},
[key]
);
return [value, setStoredValue, loading];
}
export default useAsyncStorage;