Created
February 22, 2019 13:21
-
-
Save ronal2do/623edbdce965b8de4e8172f7dab448df to your computer and use it in GitHub Desktop.
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 { AsyncStorage } from 'react-native' | |
import react, { useEffect } from "react" | |
import { useState } from 'react' | |
import { useNetInfo } from './useNetInfo'; | |
export const getData = async (key: string) => { | |
try { | |
const value = await AsyncStorage.getItem(key) | |
if (value !== null) { | |
return JSON.parse(value) | |
} | |
} catch (e) { | |
// error reading value | |
} | |
} | |
export const storeData = async (state: object, key: string) => { | |
try { | |
await AsyncStorage.setItem(key, JSON.stringify(state)) | |
return true | |
} catch (e) { | |
console.warn('error', e) | |
} | |
} | |
function useAsyncEffect(effect: () => Promise<void | (() => void)>, dependencies?: any[]) { | |
return useEffect(() => { | |
const cleanupPromise = effect() | |
return () => { cleanupPromise.then(cleanup => cleanup && cleanup()) } | |
}, dependencies) | |
} | |
export const usePersistFetch = (url: string): any => { | |
const [data, setData] = useState() | |
const [loading, setLoading] = useState(true) | |
const netInfo = useNetInfo() | |
const { type } = netInfo | |
useAsyncEffect(async () => { | |
if (type === 'wifi' || type === 'cellular') { | |
const response = await fetch(`https://jsonplaceholder.typicode.com/${url}`) | |
const data = await response.json() | |
storeData(data, url) | |
} | |
const off = await getData(url) | |
setData(off) | |
setLoading(false) | |
}, [url]) | |
return { | |
data, | |
loading | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment