Skip to content

Instantly share code, notes, and snippets.

@ronal2do
Created February 22, 2019 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronal2do/623edbdce965b8de4e8172f7dab448df to your computer and use it in GitHub Desktop.
Save ronal2do/623edbdce965b8de4e8172f7dab448df to your computer and use it in GitHub Desktop.
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