Created
August 16, 2020 18:55
-
-
Save simicd/52261f5c32a828e389257d23bf75e006 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, useCallback } from "react"; | |
| interface RequestProps<T> { | |
| url: RequestInfo; | |
| init?: RequestInit; | |
| processData?: (data: any) => T; | |
| } | |
| export const useFetch = <T>({ url, init, processData }: RequestProps<T>) => { | |
| // Response state | |
| const [data, setData] = useState<T>(); | |
| // ... | |
| // If no processing function is passed just cast the object to type T | |
| // The callback hook ensures that the function is only created once | |
| // and hence the effect hook below doesn't start an infinite loop | |
| const processJson = useCallback(processData || ((jsonBody: any) => jsonBody as T), []); | |
| useEffect(() => { | |
| // ... | |
| }, [stringifiedUrl, stringifiedInit, processJson]); | |
| return data; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment