-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseServices.js
61 lines (54 loc) · 1.67 KB
/
useServices.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { useEffect, useReducer, useRef, useCallback } from "react";
import useStorage from "./useStorage";
const initialState = {
response: null,
loading: false,
error: null,
};
function reducer(_, { type, payload }) {
switch (type) {
case "REQUEST":
return { ...initialState, loading: true };
case "SUCCESS":
return { ...initialState, response: payload };
case "ERROR":
return { ...initialState, error: payload };
default:
return initialState;
}
}
export default function useService(axios, url, options = {}) {
const [state, dispatch] = useReducer(reducer, initialState);
const [cache, setCache] = useStorage("cache", {}, true);
const abortControllerRef = useRef(null);
useEffect(() => {
abortControllerRef.current = new AbortController();
return () => {
abortControllerRef.current?.abort();
};
}, []);
const execute = useCallback(
async (params) => {
const method = options.method?.toLowerCase() || "get";
const signal = abortControllerRef.current.signal;
if (options.cache && cache[url]) {
dispatch({ type: "SUCCESS", payload: cache[url] });
} else {
dispatch({ type: "REQUEST" });
try {
const { data } = await axios[method](url,
method !== "get" ? { ...params } : { params },
{ signal });
dispatch({ type: "SUCCESS", payload: data });
if (options.cache) setCache((prev) => ({ ...prev, [url]: data }));
} catch (error) {
if (!signal.aborted) {
dispatch({ type: "ERROR", payload: error.response });
}
}
}
},
[cache, url]
);
return [state, execute];
}