Created
June 19, 2025 11:15
-
-
Save denniske/e23513bb3c1f6208742c83f69688f85b to your computer and use it in GitHub Desktop.
useAsyncStorageValue
This file contains hidden or 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 useAsyncStorageValue<T>(key: string) { | |
const [value, setValue] = useState<T>(); | |
const { getItem, setItem } = useAsyncStorage(key); | |
const readItemFromStorage = async () => { | |
const item = await getItem(); | |
setValue(item != null ? JSON.parse(item) : null); | |
}; | |
const writeItemToStorage = async (newValue: T) => { | |
await setItem(JSON.stringify(newValue)); | |
setValue(newValue); | |
}; | |
useEffect(() => { | |
readItemFromStorage(); | |
}, []); | |
return [value, writeItemToStorage] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment