Skip to content

Instantly share code, notes, and snippets.

@msukmanowsky
Last active December 29, 2022 09:13
Show Gist options
  • Save msukmanowsky/08a3650223dda8b102d2c9fe94ad5c12 to your computer and use it in GitHub Desktop.
Save msukmanowsky/08a3650223dda8b102d2c9fe94ad5c12 to your computer and use it in GitHub Desktop.
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