-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-hooks.js
More file actions
77 lines (36 loc) · 1.02 KB
/
api-hooks.js
File metadata and controls
77 lines (36 loc) · 1.02 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useState, useEffect, useCallback } from 'react';
// 1st function
export const fetchAPI = async (url, options) => {
try {
const response = await fetch(url, options);
if (!response.ok) {
new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
};
// 2nd function
export const useFetch = (url, options) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await fetchAPI(url, options);
setData(result.data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}, [url, options]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch: fetchData };
};