|
1 |
| -import axios from 'axios'; |
2 |
| -import { useEffect, useState } from 'react'; |
3 |
| - |
4 |
| -interface Post { |
5 |
| - id: number; |
6 |
| - title: string; |
7 |
| - body: string; |
8 |
| - userId: number; |
9 |
| -} |
| 1 | +import { useState } from "react"; |
| 2 | +import usePosts from "./hooks/usePosts"; |
| 3 | +import React from "react"; |
10 | 4 |
|
11 | 5 | const PostList = () => {
|
12 |
| - const [posts, setPosts] = useState<Post[]>([]); |
13 |
| - const [error, setError] = useState(''); |
| 6 | + const pageSize = 10; |
| 7 | + const { data, error, isLoading, fetchNextPage, isFetchingNextPage } = |
| 8 | + usePosts({ pageSize }); |
14 | 9 |
|
15 |
| - useEffect(() => { |
16 |
| - axios |
17 |
| - .get('https://jsonplaceholder.typicode.com/posts') |
18 |
| - .then((res) => setPosts(res.data)) |
19 |
| - .catch((error) => setError(error)); |
20 |
| - }, []); |
| 10 | + if (error) return <p>{error.message}</p>; |
21 | 11 |
|
22 |
| - if (error) return <p>{error}</p>; |
| 12 | + if (isLoading) return <p>Loading...</p>; |
23 | 13 |
|
24 | 14 | return (
|
25 |
| - <ul className="list-group"> |
26 |
| - {posts.map((post) => ( |
27 |
| - <li key={post.id} className="list-group-item"> |
28 |
| - {post.title} |
29 |
| - </li> |
30 |
| - ))} |
31 |
| - </ul> |
| 15 | + <> |
| 16 | + <ul className="list-group"> |
| 17 | + {data.pages.map((page, index) => ( |
| 18 | + <React.Fragment key={index}> |
| 19 | + {page.map((post) => ( |
| 20 | + <li key={post.id} className="list-group-item"> |
| 21 | + {post.title} |
| 22 | + </li> |
| 23 | + ))} |
| 24 | + </React.Fragment> |
| 25 | + ))} |
| 26 | + </ul> |
| 27 | + <button |
| 28 | + className="btn btn-primary my-3 ms-1" |
| 29 | + disabled={isFetchingNextPage} |
| 30 | + onClick={() => fetchNextPage()} |
| 31 | + > |
| 32 | + {isFetchingNextPage ? "Loading" : "Load More"} |
| 33 | + </button> |
| 34 | + </> |
32 | 35 | );
|
33 | 36 | };
|
34 | 37 |
|
|
0 commit comments