Last active
December 23, 2019 13:35
-
-
Save dsdenes/83b91fe9f14260997d447bd9d61c883b 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
export interface Gist { | |
url: string | |
} | |
export const useGists = (page: number = 0): [Gist[] | null, string?] => { | |
const [gists, setGists] = useState(null) | |
const [error, setError] = useState() | |
useEffect(() => { | |
let mounted = true | |
setError(null) | |
fetchGists(page) | |
.then(gists => { | |
if (mounted) { | |
setGists(gists) | |
} | |
}) | |
.catch(err => { | |
if (mounted) { | |
setError(err.message) | |
} | |
}) | |
return () => mounted = false | |
}, [page]) | |
return [gists, error] | |
} | |
async function fetchGists(page: number): Promise<Gist[]> { | |
return new Promise((resolve, reject) => { | |
fetch(`https://api.github.com/gists/public?per_page=5&page=${page}`) | |
.then(response => resolve(response.json())) | |
.catch(err => reject(err)) | |
.finally(() => fetching = null) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment