-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.js
105 lines (91 loc) · 2.13 KB
/
fetch.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { useState, useEffect, useCallback } from 'react';
import { createHook } from 'hookleton';
const URL = 'https://randomuser.me/api/?results=10';
const useFetchUsers = createHook(() => {
const [users, setUsers] = useState({});
const [again, updater] = useState();
async function fetchData() {
const response = await fetch(URL);
const data = await response.json();
console.log('[useFetch]: Fetched 10 random users');
setUsers(data);
}
useEffect(() => {
fetchData();
}, [again]);
const fetchAgain = useCallback(() => updater(s => ~s), []);
return [users, fetchAgain];
});
const Hookletons = () => {
useFetchUsers.use();
return null;
};
const RenderUser = ({ render }) => {
const [data, fetchAgain] = useFetchUsers();
return (
<ul style={{ listStyle: 'none', borderStyle: 'solid' }}>
{data.results ? (
data.results.map((user, idx) => (
<li key={idx}>
<span>{idx}: </span>
{render(user)}
<br />
</li>
))
) : (
<span>loading...</span>
)}
<li>
<button onClick={fetchAgain}>fetch Again</button>
</li>
</ul>
);
};
const Name = ({ name }) => (
<span>
{name.first} {name.last}
</span>
);
const Gender = ({ gender }) => <span>{gender}</span>;
const Location = ({ location }) => (
<span>
{location.city}, {location.state}
</span>
);
const Email = ({ email }) => <span>{email}</span>;
const Users = () => (
<table>
<tbody>
<tr>
<td>
<RenderUser render={Name} />
</td>
<td>
<RenderUser render={Gender} />
</td>
<td>
<RenderUser render={Location} />
</td>
<td>
<RenderUser render={Email} />
</td>
</tr>
</tbody>
</table>
);
// Repeat `Users` component 4 times
export default () => (
<>
<Hookletons />
<h1>
Fetched 10 random users from: <span>{URL}</span>
</h1>
<ul style={{ listStyle: 'none' }}>
{Array.from({ length: 4 }).map((_, idx) => (
<li key={idx}>
<Users />
</li>
))}
</ul>
</>
);