Last active
December 29, 2022 09:13
-
-
Save msukmanowsky/08a3650223dda8b102d2c9fe94ad5c12 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
import { useState, useEffect } from "react"; | |
import { AsyncStorage } from "react-native"; | |
function useAsyncStorage(key, initialValue) { | |
const [storedValue, setStoredValue] = useState(initialValue); | |
useEffect(() => { | |
AsyncStorage.getItem(key) | |
.then(value => { | |
if (value === null) return initialValue; | |
return JSON.parse(value); | |
}) | |
.then(setStoredValue) | |
}, [key, initialValue]); | |
const setValue = value => { | |
const valueToStore = value instanceof Function ? value(storedValue) : value; | |
setStoredValue(valueToStore); | |
AsyncStorage.setItem(key, JSON.stringify(valueToStore)); | |
} | |
return [storedValue, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment