Created
September 24, 2019 19:37
-
-
Save brionmario/10f793771cc1a1b24917481fe2b01fdd to your computer and use it in GitHub Desktop.
Custom API hook to handle network requests
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 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