@@ -5,9 +5,13 @@ import { useHistory } from 'react-router';
5
5
import LoadingSpinner from '../components/LoadingSpinner' ;
6
6
import { bool } from 'prop-types' ;
7
7
import Pagination from './Pagination' ;
8
+ import { useLocation } from 'react-router-dom' ;
8
9
9
10
const BlogList = ( { isAdmin } ) => {
10
11
const history = useHistory ( ) ;
12
+ const location = useLocation ( ) ;
13
+ const params = new URLSearchParams ( location . search ) ;
14
+ const pageParam = params . get ( 'page' ) ;
11
15
const [ posts , setPosts ] = useState ( [ ] ) ;
12
16
const [ loading , setLoading ] = useState ( true ) ;
13
17
const [ currentPage , setCurrentPage ] = useState ( 1 ) ;
@@ -19,8 +23,10 @@ const BlogList = ({ isAdmin }) => {
19
23
setNumberOfPages ( Math . ceil ( numberOfPosts / limit ) ) ;
20
24
} , [ numberOfPosts ] ) ;
21
25
26
+ const onClickPageButton = ( page ) => {
27
+ history . push ( `${ location . pathname } ?page=${ page } ` )
28
+ }
22
29
const getPosts = ( page = 1 ) => {
23
- setCurrentPage ( page ) ;
24
30
let params = {
25
31
_page : page ,
26
32
_limit : limit ,
@@ -41,17 +47,18 @@ const BlogList = ({ isAdmin }) => {
41
47
} )
42
48
}
43
49
50
+ useEffect ( ( ) => {
51
+ setCurrentPage ( parseInt ( pageParam ) || 1 ) ;
52
+ getPosts ( parseInt ( pageParam ) || 1 ) ;
53
+ } , [ pageParam ] ) ;
54
+
44
55
const deleteBlog = ( e , id ) => {
45
56
e . stopPropagation ( ) ;
46
57
47
58
axios . delete ( `http://localhost:3001/posts/${ id } ` ) . then ( ( ) => {
48
59
setPosts ( prevPosts => prevPosts . filter ( post => post . id !== id ) ) ;
49
60
} ) ;
50
61
} ;
51
-
52
- useEffect ( ( ) => {
53
- getPosts ( ) ;
54
- } , [ ] ) ;
55
62
56
63
if ( loading ) {
57
64
return (
@@ -89,7 +96,7 @@ const BlogList = ({ isAdmin }) => {
89
96
{ numberOfPages > 1 && < Pagination
90
97
currentPage = { currentPage }
91
98
numberOfPages = { numberOfPages }
92
- onClick = { getPosts }
99
+ onClick = { onClickPageButton }
93
100
/> }
94
101
</ div >
95
102
)
0 commit comments