Created
March 20, 2023 12:43
-
-
Save makomweb/b52644ed5df0145323889ea7df0ab404 to your computer and use it in GitHub Desktop.
HTTP GET hook
This file contains 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 { useEffect, useState } from 'react'; | |
import axios from 'axios'; | |
type State<T> = { | |
pending: boolean; | |
error?: Error; | |
data?: T; | |
}; | |
export function useGet<T>(url: string) { | |
const [state, setState] = useState<State<T>>({ | |
pending: true, | |
error: undefined, | |
data: undefined, | |
}); | |
useEffect(() => { | |
axios | |
.get(url) | |
.then(response => setState({ pending: false, data: response.data as T, error: undefined }) | |
.catch(error => setState({ pending: false, data: undefined, error: error }); | |
}, []); | |
return { ...state }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment