-
Notifications
You must be signed in to change notification settings - Fork 1
/
PostListFetch.tsx
68 lines (57 loc) · 1.52 KB
/
PostListFetch.tsx
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
import { useEffect, useState } from 'react';
import { Post } from './Post';
import './PostList.css';
type Props = {
limit?: number;
page?: number;
};
function PostListFetch({ limit = 5, page: initialPage = 1 }: Props) {
const [posts, setPosts] = useState<Post[]>([]);
const [page, setPage] = useState<number>(initialPage);
const [error, setError] = useState<string>('');
useEffect(() => {
fetch(
`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
)
.then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
}
return response.json();
})
.then((data) => setPosts(data))
.catch((err) => setError(err.message));
}, [limit, page]);
const renderPageList = (start: number, end: number) => {
const list = [];
for (let pageNumber = start; pageNumber <= end; pageNumber++) {
list.push(
<button
key={pageNumber}
className={pageNumber === page ? 'active' : ''}
onClick={() => setPage(pageNumber)}
>
{pageNumber}
</button>
);
}
return list;
};
return (
<>
<div>
<h1>Post list</h1>
<ul>
{posts.map((post: Post) => (
<li key={post.id}>{[post.title]}</li>
))}
</ul>
</div>
{ error && <p className='error'>{error}</p>}
<div>
<div className="page-list">{renderPageList(1, 10)}</div>
</div>
</>
);
}
export default PostListFetch;