Skip to content

Instantly share code, notes, and snippets.

@coreyward
Created July 26, 2020 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreyward/df6756dbf8925aa7041220b43b1e56d2 to your computer and use it in GitHub Desktop.
Save coreyward/df6756dbf8925aa7041220b43b1e56d2 to your computer and use it in GitHub Desktop.
Async Storage backed `useState` for React Native
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