Skip to content

Instantly share code, notes, and snippets.

@NickWickedSick
Forked from msukmanowsky/use-async-storage.js
Created January 23, 2020 11:43
Show Gist options
  • Save NickWickedSick/9157c46187b46a665b295cae03d57b1a to your computer and use it in GitHub Desktop.
Save NickWickedSick/9157c46187b46a665b295cae03d57b1a 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