Skip to content

Instantly share code, notes, and snippets.

@dsdenes
Last active December 23, 2019 13:35
Show Gist options
  • Save dsdenes/83b91fe9f14260997d447bd9d61c883b to your computer and use it in GitHub Desktop.
Save dsdenes/83b91fe9f14260997d447bd9d61c883b to your computer and use it in GitHub Desktop.
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