Created
July 26, 2020 19:32
-
-
Save coreyward/df6756dbf8925aa7041220b43b1e56d2 to your computer and use it in GitHub Desktop.
Async Storage backed `useState` for React Native
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, useCallback } from "react"; | |
import { useAsyncStorage } from "@react-native-community/async-storage"; | |
/** | |
* @example | |
* const [isReady, setReady, refresh] = usePersistantState(199, "ready") | |
*/ | |
export default (id, property, defaultValue = null) => { | |
const [value, setValue] = useState(defaultValue); | |
const { getItem, setItem } = useAsyncStorage(`${id}#${property}`); | |
const fetchFromStorage = useCallback(async () => { | |
const data = await getItem(); | |
const item = JSON.parse(data) || { value: defaultValue }; | |
console.debug(`Read ${item.value} for ${id}#${property}`); | |
setValue(item.value); | |
}, [id, property, defaultValue]); | |
const setter = useCallback( | |
async (newValue) => { | |
setValue(newValue); | |
await setItem(JSON.stringify({ value: newValue })); | |
console.debug(`Saved ${newValue} for ${id}#${property}`); | |
}, | |
[id, property] | |
); | |
useEffect(() => { | |
fetchFromStorage(); | |
}, []); | |
return [value, setter, fetchFromStorage]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment