Created
August 24, 2022 02:37
-
-
Save BlazeIsClone/abe7f32efb16d3d8058e8f7b37e7e72c to your computer and use it in GitHub Desktop.
React Axios Custom Query 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 axios, { AxiosError, AxiosRequestHeaders } from 'axios'; | |
import { useEffect, useState } from 'react'; | |
import { RequestConfigI, ResponseT } from './useQuery.types'; | |
import { instance } from 'services'; | |
export const useQuery: RequestConfigI<ResponseT> = ( | |
resource, | |
data, | |
extraHeaders | |
) => { | |
const [headers, setHeaders] = useState<AxiosRequestHeaders>({}); | |
const [error, setError] = useState<AxiosError | false>(false); | |
const [loading, setLoading] = useState(true); | |
const [response, setResponse] = useState({}); | |
const [payload, setPayload] = useState({}); | |
const [url, setUrl] = useState('/'); | |
useEffect(() => { | |
const controller = new AbortController(); | |
if (resource) setUrl(resource); | |
if (data) setPayload({ ...data }); | |
if (extraHeaders) setHeaders({ ...extraHeaders }); | |
(async () => { | |
try { | |
const response = await instance(url, { | |
signal: controller.signal, | |
data: payload, | |
headers, | |
}); | |
setResponse(response); | |
} catch (error) { | |
axios.isAxiosError(error) && setError(error); | |
} finally { | |
setLoading(false); | |
} | |
})(); | |
return () => controller.abort(); | |
}, [data, extraHeaders, headers, payload, resource, url]); | |
return { response, loading, error }; | |
}; |
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 { AxiosError, AxiosRequestHeaders } from 'axios'; | |
export interface RequestConfigI<ResponseType> { | |
( | |
resource: string, | |
data?: object, | |
extraHeaders?: AxiosRequestHeaders | |
): ResponseType; | |
} | |
export type ResponseT = { | |
response: object; | |
oading: boolean; | |
error: AxiosError | false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment