import { useState, useEffect } from "react";
import axios from "axios";
import { BASE_URL } from "config/api";
axios.defaults.baseURL = BASE_URL;
const useAxios = ({ url, method, body = null, headers = null }) => {
const [data, setData] = useState(null);
const [message, setMessage] = useState("");
const [error, setError] = useState("");
const [loading, setloading] = useState(true);
const fetchData = () => {
axios[method](url, JSON.parse(headers), JSON.parse(body))
.then(({ data: resBody }) => {
setData(resBody.data);
setMessage(resBody.message);
})
.catch((err) => setError(err))
.finally(() => setloading(false));
};
useEffect(() => {
fetchData();
}, [method, url, body, headers]);
return { data, error, loading, message };
};
export default useAxios;
Axios custom hook
All In OneThe code helps to make a custom hook to use axios to make any type of API calls so, that you don't have to write the generic code everytime you want to use axios.
Shortcut: useAxios
0 Comments
Add Comment
Log in to add a comment