-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathList.js
38 lines (32 loc) · 1.12 KB
/
List.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
import React, { useState, useEffect } from 'react';
const List = () => {
const [listItems, setListItems] = useState(Array.from(Array(30).keys(), n => n + 1));
const [isFetching, setIsFetching] = useState(false);
useEffect(() => {
function handleScroll() {
if (Math.ceil(window.innerHeight + document.documentElement.scrollTop) !== document.documentElement.offsetHeight || isFetching) return;
setIsFetching(true);
}
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
useEffect(() => {
if (!isFetching) return;
fetchMoreListItems();
}, [isFetching]);
function fetchMoreListItems() {
setTimeout(() => {
setListItems(prevState => ([...prevState, ...Array.from(Array(20).keys(), n => n + prevState.length + 1)]));
setIsFetching(false);
}, 2000);
}
return (
<>
<ul className="list-group mb-2">
{listItems.map(listItem => <li className="list-group-item">List Item {listItem}</li>)}
</ul>
{isFetching && 'Fetching more list items...'}
</>
);
};
export default List;