forked from guillaumervls/react-infinite-scroll
-
Notifications
You must be signed in to change notification settings - Fork 513
/
Copy pathindex.js
83 lines (70 loc) · 1.77 KB
/
index.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
import React, { useCallback, useState } from 'react';
import { createRoot } from 'react-dom/client';
import InfiniteScroll from 'react-infinite-scroller';
import parseLinkHeader from 'parse-link-header';
async function fetchIssues(url) {
const response = await fetch(url, {
method: 'GET',
headers: new Headers({
Accept: 'application/vnd.github.v3+json'
})
});
const links = parseLinkHeader(response.headers.get('Link'));
const issues = await response.json();
return {
links,
issues
};
}
const App = () => {
const [items, setItems] = useState([]);
const [nextPageUrl, setNextPageUrl] = useState(
'https://api.github.com/repos/facebook/react/issues'
);
const [fetching, setFetching] = useState(false);
const fetchItems = useCallback(
async () => {
if (fetching) {
return;
}
setFetching(true);
try {
const { issues, links } = await fetchIssues(nextPageUrl);
setItems([...items, ...issues]);
if (links.next) {
setNextPageUrl(links.next.url);
} else {
setNextPageUrl(null);
}
} finally {
setFetching(false);
}
},
[items, fetching, nextPageUrl]
);
const hasMoreItems = !!nextPageUrl;
const loader = (
<div key="loader" className="loader">
Loading ...
</div>
);
return (
<InfiniteScroll
loadMore={fetchItems}
hasMore={hasMoreItems}
loader={loader}
>
<ul>
{items.map(item => (
<li key={item.id}>
<a href={item.url} target="_blank" rel="noopener">
{item.title}
</a>
</li>
))}
</ul>
</InfiniteScroll>
);
};
const root = createRoot(document.getElementById('root'));
root.render(<App />);