Created
October 27, 2021 21:37
-
-
Save caoer/0f9be2c1a1ab4833f5b87e831c114f3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useAsyncStorage(key: string, initialValue: string | null = null) { | |
const [storageItem, setStorageItem] = useState<string | null>(initialValue); | |
const updateStorageItem = useCallback( | |
function (data: string) { | |
void AsyncStorage.setItem(key, data).catch(e => | |
console.log(`updateStorageItem error: ${e}`), | |
); | |
setStorageItem(data); | |
return data; | |
}, | |
[key], | |
); | |
const clearStorageItem = useCallback( | |
function () { | |
void AsyncStorage.removeItem(key).catch(e => | |
console.log(`clearStorageItem error: ${e}`), | |
); | |
setStorageItem(null); | |
}, | |
[key], | |
); | |
const getStorageItem = useCallback( | |
async function () { | |
const data = (await AsyncStorage.getItem(key)) as string | null; | |
setStorageItem(data); | |
}, | |
[key], | |
); | |
useEffect(() => { | |
getStorageItem().catch(e => console.log(`getStorageItem error: ${e}`)); | |
}, [getStorageItem]); | |
return [storageItem, updateStorageItem, clearStorageItem] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment