Skip to content

Instantly share code, notes, and snippets.

@caoer
Created October 27, 2021 21:37
Show Gist options
  • Save caoer/0f9be2c1a1ab4833f5b87e831c114f3c to your computer and use it in GitHub Desktop.
Save caoer/0f9be2c1a1ab4833f5b87e831c114f3c to your computer and use it in GitHub Desktop.
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