-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetch.js
39 lines (38 loc) · 1.05 KB
/
useFetch.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
import React, { useState, useEffect } from "react";
import Axios from "axios";
import { Config } from "../Config";
const useFetch = (url, options, setData) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
let baseUrl = `${Config.API_URL}${url}?${Config.API_KEY}&language=en-US&page=1`;
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const doFetch = async () => {
setLoading(true);
try {
const json = await Axios.get(baseUrl);
if (!signal.aborted) {
setResponse(json);
setData(json);
}
} catch (e) {
console.log({ e });
if (!signal.aborted) {
setError(e);
}
} finally {
if (!signal.aborted) {
setLoading(false);
}
}
};
doFetch();
return () => {
abortController.abort();
};
}, []);
return { response, error, loading };
};
export default useFetch;