-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadMoreButton.jsx
72 lines (66 loc) · 1.88 KB
/
LoadMoreButton.jsx
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
import { useEffect, useState } from "react";
import styles from "./LoadMoreButton.module.css";
export default function LoadMoreButton({
url = "https://dummyjson.com/products",
limit = 3,
total = 9,
}) {
const [loading, setLoading] = useState(false);
const [products, setProducts] = useState([]);
const [count, setCount] = useState(0);
const [disable, setDisable] = useState(false);
async function fetchProducts() {
try {
setLoading(true);
const response = await fetch(
`${url}?limit=${limit}&skip=${count * limit}`
);
const result = await response.json();
if (result && result.products && result.products.length) {
console.log(result);
setProducts((prevProducts) => {
const nextProducts = [...prevProducts, ...result.products];
if (nextProducts.length >= total) {
setDisable(true);
return nextProducts.slice(0, total);
} else {
return nextProducts;
}
});
}
} catch (e) {
console.log(e);
} finally {
setLoading(false);
}
}
useEffect(() => {
fetchProducts();
}, [count]);
if (loading) {
return <div>Loading</div>;
}
return (
<div className={styles.wrapper}>
<div className={styles.itemContainer}>
{products && products.length
? products.map((item) => (
<div key={item.id} className={styles.item}>
<img
className={styles.itemThumbnail}
src={item.thumbnail}
></img>
<div>{item.title}</div>
</div>
))
: null}
</div>
<div className={styles.buttonContainer}>
<button disabled={disable} onClick={() => setCount(count + 1)}>
Load More
</button>
{disable && <p>Reached Page End</p>}
</div>
</div>
);
}