Skip to content

Instantly share code, notes, and snippets.

@AdithyaBhat17
Created July 30, 2019 15:06
Show Gist options
  • Save AdithyaBhat17/2bcd785763a41e0fe0a16b8b43443007 to your computer and use it in GitHub Desktop.
Save AdithyaBhat17/2bcd785763a41e0fe0a16b8b43443007 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react'
export const useFetch = (url) => {
const [data, setData] = useState(undefined)
const [loading, setLoading] = useState(false)
useEffect(() => {
// loading set to true for spinner to show up
setLoading(true)
// make the api call
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'token': localStorage.getItem('Authorization')
}
})
.then(response => response.json())
// where the magic happens
.then(data => {
setData(data)
setLoading(false)
})
// where the sadness hits the roof
.catch(error => console.error(error))
}, [url]) // dependency array to call the lifecycle event once again if the url changes.
// return these bad boys to the RFC.
return [data, loading]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment