-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAxiosFunction.js
More file actions
39 lines (31 loc) · 1.07 KB
/
useAxiosFunction.js
File metadata and controls
39 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useState, useEffect } from "react";
export const useAxiosFunction = () => {
const [response, setResponse] = useState([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [controller, setController] = useState();
const axiosFetch = async (config) => {
const { axiosInstance, method, url, requestConfig = {} } = config;
try {
setLoading(true);
const ctrl = new AbortController();
setController(ctrl);
const res = await axiosInstance[method.toLowerCase()](url, {
...requestConfig,
signal: ctrl.signal,
});
console.log(res);
setResponse(res.data);
} catch (err) {
console.log(err.message);
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
console.log(controller);
return () => controller?.abort();
}, [controller]);
return [response, error, loading, axiosFetch];
};