-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCustomHook.tsx
50 lines (42 loc) · 1.15 KB
/
CustomHook.tsx
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
import { useEffect, useState } from 'react';
import { Book } from '../book/interfaces';
const useFetchDataFromAPI = (url: string, timeout: number = 2000) => {
const [data, setData] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch(url)
.then((response) => response.json())
.then((data: Book[]) => {
const books = data.reduce((result, book) => {
return result.concat(book.title);
}, [] as string[]);
setTimeout(() => {
setData(books);
setLoading(false);
}, timeout);
});
}, [url, timeout]);
return [data, loading];
};
const Children = () => {
const [data, loading] = useFetchDataFromAPI('http://localhost:4730/books', 5000);
return (
<>
<h2>Value in children</h2>
<h4>Data: {JSON.stringify(data)}</h4>
<h4>Loading: {loading ? 'Pending…' : 'Done!'}</h4>
</>
);
};
export default function CustomHook() {
const [data, loading] = useFetchDataFromAPI('http://localhost:4730/books');
return (
<>
<h2>Custom Hook</h2>
<h4>Data: {JSON.stringify(data)}</h4>
<h4>Loading: {loading ? 'Pending…' : 'Done!'}</h4>
<Children />
</>
);
}