App.js
import React from 'react'
import Part from './component/Part'
const App = () => {
return (
<div>
<h1><Part /></h1>
</div>
)
}
export default App
Part.js
import React from 'react'
import useAxios from '../hooks/useAxios';
import axios from '../api/axiosinstance';
const Part = () => {const[chil,error,loading,refetch] = useAxios({
axiosInstance:axios,
method:'GET',
url:'/',
requestConfig:{
hesders:{
'Content-Language':'en-US'
}
}
})
return (
<div>
<h4>Axios Requests</h4>
{loading && <p>Loading...</p>}
{!loading && error && <p className='errMsg'>{error}</p>}
{!loading && !error && chil && <p>{chil?.chil}</p>}
{!loading && !error && !chil && <p>No data display</p>}
<button onclick={() => refetch()}>Test</button>
</div>
)
}
export default Part
useAxios.js
import { useState, useEffect } from "react";
const useAxios = (configObj) => {
const {
axiosInstance,
method,
url,
requestConfig = {}
} = configObj;
const [response, setResponse] = useState([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [reload, setReload] = useState(0);
const refetch = () => setReload(prev => prev + 1);
useEffect(() => {
//let isMounted = true;
const controller = new AbortController();
const fetchData = async () => {
try {
const res = await iosInstance[method.toLowerCase()](url, {
...requestConfig,
signal: controller.signal
});
console.log(res);
setResponse(res.data);
} catch (err) {
console.log(err.message);
setError(err.message);
} finally {
setLoading(false);
}
}
fetchData();
return () => controller.abort();
// eslint-disable-next-line
}, [reload]);
return [response, error, loading, refetch];
}
export default useAxios
axiosinstance.js
import axios from 'axios';
const BASE_URL = 'https://icanhazdadjoke.com';
export default axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});