Skip to content

Instantly share code, notes, and snippets.

@brionmario
Created September 24, 2019 19:37
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 brionmario/10f793771cc1a1b24917481fe2b01fdd to your computer and use it in GitHub Desktop.
Save brionmario/10f793771cc1a1b24917481fe2b01fdd to your computer and use it in GitHub Desktop.
Custom API hook to handle network requests
import axios, { AxiosRequestConfig } from "axios";
import React, { useEffect, useState } from "react";
import { HttpError, HttpRequestConfig, HttpResponse } from "../models/api";
/**
* Custom API hook to handle network requests.
*
* @param {HttpRequestConfig} config
* @param {(response: HttpResponse) => void} onSuccessCallback
* @param {(error: HttpError) => void} onErrorCallback
* @return {any[]}
*/
export const useAPI = (
config: HttpRequestConfig,
onSuccessCallback?: (response: HttpResponse) => void,
onErrorCallback?: (error: HttpError) => void
) => {
const [ response, setResponse ] = useState(null);
const [ isLoading, setIsLoading ] = useState(false);
const [ error, setError ] = useState(null);
const fetchData = () => {
setIsLoading(true);
makeAxiosRequest(config)
.then((res) => {
setResponse(res);
onSuccessCallback(res);
})
.catch((err) => {
setError(err);
onErrorCallback(err);
});
};
useEffect(() => {
fetchData();
}, []);
return [ response, isLoading, error, fetchData ];
};
/**
*
* @param {AxiosRequestConfig} config
* @return {AxiosPromise<any>}
*/
const makeAxiosRequest = (config: AxiosRequestConfig) => {
return axios.request(config);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment