Created
December 19, 2022 04:43
-
-
Save dclstn/4a22b84bfb7d4ff5e1e57b1dd5f26690 to your computer and use it in GitHub Desktop.
useApi React Hook
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 React from "react"; | |
| interface Response<T> { | |
| data: T | null; | |
| isFetching: boolean; | |
| error: string | null; | |
| isSuccess: boolean; | |
| } | |
| export function useApi<T>(apiFunction: () => Promise<any>): [Response<T>, () => void] { | |
| const [response, setResponse] = React.useState<Response<T>>({ | |
| data: null, | |
| isFetching: false, | |
| error: null, | |
| isSuccess: false, | |
| }); | |
| const callback = React.useCallback(async () => { | |
| setResponse({ | |
| data: null, | |
| isFetching: true, | |
| error: null, | |
| isSuccess: false, | |
| }); | |
| try { | |
| const res = await apiFunction(); | |
| setResponse({...response, data: res, isFetching: false, isSuccess: true}); | |
| } catch (err) { | |
| setResponse({...response, isFetching: false, error: (err as Error).message}); | |
| } | |
| }, [apiFunction]); | |
| return [response, callback]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment