Skip to content

Commit eb3fa0d

Browse files
committed
Enhance Pagination component with loading state and improved button handling
1 parent 715de97 commit eb3fa0d

File tree

1 file changed

+54
-21
lines changed

1 file changed

+54
-21
lines changed

‎src/Pagination.jsx‎

Lines changed: 54 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,62 @@
1-
import React from 'react'
2-
import { useGlobalContext } from './Context'
1+
import React, { useState, useCallback } from 'react';
2+
import { useGlobalContext } from './Context';
33

44
const Pagination = () => {
5-
const {page,nbPages,getPrevPage,getNextPage,setShowPopularNews,showPopularNews}=useGlobalContext();
5+
const { page, nbPages, getPrevPage, getNextPage, setShowPopularNews, showPopularNews } = useGlobalContext();
6+
const [isLoading, setIsLoading] = useState(false);
7+
8+
const handlePrev = useCallback(() => {
9+
if (!isLoading) {
10+
setIsLoading(true);
11+
getPrevPage();
12+
setTimeout(() => setIsLoading(false), 300);
13+
}
14+
}, [getPrevPage, isLoading]);
15+
16+
const handleNext = useCallback(() => {
17+
if (!isLoading) {
18+
setIsLoading(true);
19+
getNextPage();
20+
setTimeout(() => setIsLoading(false), 300);
21+
}
22+
}, [getNextPage, isLoading]);
23+
624
return (
725
<>
8-
{
9-
!showPopularNews &&
10-
<div className='pagination-btn'>
11-
<button onClick={()=>getPrevPage()}>Prev</button>
12-
<p>{page+1} of {nbPages}</p>
13-
<button onClick={()=>getNextPage()}>Next</button>
14-
</div>
15-
}
16-
<div className='popular-btn'>
17-
<button onClick={()=>setShowPopularNews(!showPopularNews)} style={{ margin : '2rem'}}>
1826
{
19-
!showPopularNews
20-
? 'Trending Tech News'
21-
: 'Back to Home'
27+
!showPopularNews && (
28+
<div className="pagination-btn">
29+
<button
30+
onClick={handlePrev}
31+
disabled={page <= 0 || isLoading}
32+
className={isLoading ? 'loading' : ''}
33+
>
34+
Prev
35+
</button>
36+
37+
<p>{page + 1} of {nbPages}</p>
38+
39+
<button
40+
onClick={handleNext}
41+
disabled={page >= nbPages - 1 || isLoading}
42+
className={isLoading ? 'loading' : ''}
43+
>
44+
Next
45+
</button>
46+
</div>
47+
)
2248
}
23-
</button>
24-
</div>
49+
50+
<div className="popular-btn">
51+
<button
52+
onClick={() => setShowPopularNews(!showPopularNews)}
53+
style={{ margin: '2rem' }}
54+
>
55+
{ !showPopularNews ? '🔥 Trending Tech News' : '🏠 Back to Home' }
56+
</button>
57+
</div>
2558
</>
26-
)
27-
}
59+
);
60+
};
2861

29-
export default Pagination
62+
export default Pagination;

0 commit comments

Comments
 (0)