Created
August 16, 2020 18:20
-
-
Save simicd/219be594b9e3f77b049d5f86e44dce6a 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
| // useFetch.ts | |
| import { useState, useEffect } from "react"; | |
| interface RequestProps { | |
| url: RequestInfo; | |
| init?: RequestInit; | |
| } | |
| type DogImageType = { message: string; status: string }; | |
| export const useFetch = ({ url, init }: RequestProps) => { | |
| // Response state | |
| const [data, setData] = useState<DogImageType>(); | |
| useEffect(async () => { | |
| try { | |
| // Fetch data from REST API | |
| const response = await fetch(url, init); | |
| if (response.status === 200) { | |
| // Extract json | |
| const rawData: DogImageType = await response.json(); | |
| setData(rawData); | |
| } else { | |
| console.error(`Error ${response.status} ${response.statusText}`); | |
| } | |
| } catch (error) { | |
| console.error(`Error ${error}`); | |
| } | |
| }, []); | |
| return data; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment