Skip to content

Instantly share code, notes, and snippets.

@ronal2do
Last active February 20, 2019 07:54
Show Gist options
  • Save ronal2do/2dac53b7ad6f77534d1c555c43ead1f2 to your computer and use it in GitHub Desktop.
Save ronal2do/2dac53b7ad6f77534d1c555c43ead1f2 to your computer and use it in GitHub Desktop.
// 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