Created
July 30, 2019 15:06
-
-
Save AdithyaBhat17/2bcd785763a41e0fe0a16b8b43443007 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
| 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