Last active
August 16, 2020 18:52
-
-
Save simicd/16d416399c888d31b5d7fc9756c2da0d 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; | |
| processData?: (data: any) => DogImageType | |
| } | |
| export type DogImageType = { message: string; status: string }; | |
| export const useFetch = ({ url, init, processData }: RequestProps) => { | |
| // Response state | |
| const [data, setData] = useState<DogImageType>(); | |
| // Turn objects into strings for useCallback & useEffect dependencies | |
| const [stringifiedUrl, stringifiedInit] = [JSON.stringify(url), JSON.stringify(init)]; | |
| // If no processing function is passed just cast the object to type T | |
| const processJson = processData || ((jsonBody: any) => jsonBody as DogImageType); | |
| useEffect(() => { | |
| // Define asynchronous function | |
| const fetchApi = async () => { | |
| try { | |
| // Fetch data from REST API | |
| const response = await fetch(url, init); | |
| if (response.status === 200) { | |
| // Extract json | |
| const rawData: any = await response.json(); | |
| const processedData = processJson(rawData); | |
| setData(processedData); | |
| } else { | |
| console.error(`Error ${response.status} ${response.statusText}`); | |
| } | |
| } catch (error) { | |
| console.error(`Error ${error}`); | |
| } | |
| }; | |
| // Call async function | |
| fetchApi(); | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| }, [stringifiedUrl, stringifiedInit, processJson]); | |
| return data; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment