SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 87 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect } from "react";
  2. import { AsyncStorage } from "react-native";
  3.  
  4.  
  5. function useAsyncStorage(key, initialValue) {
  6.   const [storedValue, setStoredValue] = useState(initialValue);
  7.   useEffect(() => {
  8.     AsyncStorage.getItem(key)
  9.       .then(value => {
  10.         if (value === null) return initialValue;
  11.         return JSON.parse(value);
  12.       })
  13.       .then(setStoredValue)
  14.   }, [key, initialValue]);
  15.  
  16.   const setValue = value => {
  17.     const valueToStore = value instanceof Function ? value(storedValue) : value;
  18.     setStoredValue(valueToStore);
  19.     AsyncStorage.setItem(key, JSON.stringify(valueToStore));
  20.   }
  21.  
  22.   return [storedValue, setValue];
  23. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top