Last active
February 20, 2019 07:54
-
-
Save ronal2do/2dac53b7ad6f77534d1c555c43ead1f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// useFetch.ts | |
import { useEffect, useState } from 'react' | |
export interface IPosts { | |
userId: number; | |
id: number; | |
title: string; | |
body: string; | |
} | |
interface Response { | |
loading: boolean; | |
data: IPosts; | |
} | |
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30551#issuecomment-461913188 | |
function useAsyncEffect(effect: () => Promise<void | (() => void)>, dependencies?: any[]) { | |
return useEffect(() => { | |
const cleanupPromise = effect() | |
return () => { cleanupPromise.then(cleanup => cleanup && cleanup()) } | |
}, dependencies) | |
} | |
export const useFetch = (url: string): Response => { | |
const [data, setData] = useState(null) | |
const [loading, setLoading] = useState(true) | |
// Similar to componentDidMount and componentDidUpdate: | |
useAsyncEffect(async () => { | |
const response = await fetch(url) | |
const data = await response.json() | |
setData(data) | |
setLoading(false) | |
}, [url]) // Only when url change it will update | |
return { | |
data, | |
loading | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment