Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created March 20, 2023 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makomweb/b52644ed5df0145323889ea7df0ab404 to your computer and use it in GitHub Desktop.
Save makomweb/b52644ed5df0145323889ea7df0ab404 to your computer and use it in GitHub Desktop.
HTTP GET hook
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