use-axios-http-requests-ts
Version:
Incredibly useful package for making HTTP requests! This package eliminates the need for the Fetch API and is built on top of the powerful library [axios](https://www.npmjs.com/package/axios).
50 lines (47 loc) • 1.56 kB
JavaScript
import axios, { isAxiosError } from 'axios';
import { useEffect, useState, useCallback } from 'react';
const useAxios = (url, dependencies, options) => {
const { execute, ...state } = useAxiosInternal(url, options, dependencies, true);
useEffect(() => {
execute();
}, dependencies || []);
return state;
};
const useAxiosFn = (url, options, dependencies = []) => {
return useAxiosInternal(url, options, dependencies, false);
};
const useAxiosInternal = (url, options = { method: "get" }, dependencies = [], initialLoading) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(initialLoading);
const [error, setError] = useState(null);
const execute = useCallback(async () => {
setLoading(true);
try {
const { data } = await axios(url, options);
setData(data);
}
catch (error) {
let errorObj = {
status: error.response?.status,
message: isAxiosError(error)
? error.response?.data.message
: "Some went wrong!",
};
setError(errorObj);
}
finally {
setLoading(false);
}
}, dependencies);
const refetching = () => {
setLoading(true);
setData(null);
};
const reset = () => {
setData(null);
setError(null);
setLoading(false);
};
return { data, loading, refetching, error, execute, reset };
};
export { useAxios, useAxiosFn };