I am using axios with react, so I thought to write a custom hook for this which I did and it is working fine like below
const useAxios = () => {
const [response, setResponse] = useState([]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(true); //different!
const [controller, setController] = useState();
const axiosFetch = async (configObj) => {
const { axiosInstance, method, url, requestConfig = {} } = configObj;
try {
const ctrl = new AbortController();
setController(ctrl);
const res = await axiosInstance[method.toLowerCase()](url, {
...requestConfig,
});
setResponse(res.data);
} catch (err) {
console.log(err.message);
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
console.log(controller);
// useEffect cleanup function
return () => controller && controller.abort();
}, [controller]);
return [response, error, loading, axiosFetch];
};
I have also created one axiosInstance to pass BASE_URL and headers. Now calling useAxios to fetch data from api like below
const [data, error, loading, axiosFetch] = useAxios();
const getData = () => {
axiosFetch({
axiosInstance: axios,
method: "GET",
url: "/url",
});
};
useEffect(() => {
getData();
}, []);
My Question is
- When I need to call one api I am doing above.
- But what if I have to call three or four APIs in a single page.
- Shall I replicate the code like this
const [data1, error1, loading1, axiosFetch]=useAxios();
- Or is there any other way to minimize the code.
Edit / Update
I ran above code to get data from /url
, what if I want to hit different route
to get one more data from server for other work, the base url remains the same
So if the second route is /users
const [data, error, loading, axiosFetch] = useAxios();
const getUsers = () => {
axiosFetch({
axiosInstance: axios,
method: "GET",
url: "/users",
});
};
useEffect(() => {
getUsers();
}, [on_BTN_Click]);
THe above codeI want to run in same file, one to get data and one to get users, how should I write my axios, as I think this const [data, error, loading, axiosFetch] = useAxios();
should gets called only once, Don't know how to do this or what is the correct way, shall I need to change my useAxios
hook?