Skip to content

Commit 46c6e23

Browse files
authored
Add PostList Component Example for Dynamic Data Fetching (#15)
1 parent c419170 commit 46c6e23

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

components/PostList/PostList.mdx

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { useState, useEffect } from 'react';
2+
3+
export const PostList = ({
4+
url = 'https://jsonplaceholder.typicode.com/posts?_limit=5',
5+
}) => {
6+
const [posts, setPosts] = useState([]);
7+
const [loading, setLoading] = useState(true);
8+
const [error, setError] = useState(null);
9+
10+
useEffect(() => {
11+
const fetchPosts = async () => {
12+
try {
13+
const response = await fetch(url);
14+
const data = await response.json();
15+
setPosts(data);
16+
} catch (err) {
17+
setError(err);
18+
} finally {
19+
setLoading(false);
20+
}
21+
};
22+
fetchPosts();
23+
}, [url]);
24+
25+
return (
26+
<div className="flex flex-col items-center justify-center p-10">
27+
<div className="relative w-12 h-12 mb-4">
28+
{/* Example icon or placeholder */}
29+
<span className="absolute inset-0 bg-gray-300 rounded-full" />
30+
</div>
31+
32+
{loading && <p className="text-gray-500">Loading posts…</p>}
33+
{error && <p className="text-red-500">Error loading posts.</p>}
34+
35+
<ul className="mt-4 space-y-2 w-full max-w-md">
36+
{posts.map((post) => (
37+
<li
38+
key={post.id}
39+
className="p-4 bg-white rounded shadow hover:bg-gray-50 transition"
40+
>
41+
<h3 className="font-semibold text-lg mb-1">{post.title}</h3>
42+
<p className="text-sm text-gray-600">{post.body}</p>
43+
</li>
44+
))}
45+
</ul>
46+
</div>
47+
);
48+
};
49+
50+
export default function App() {
51+
return (
52+
<div className="min-h-screen bg-gray-100 p-6">
53+
<h1 className="text-2xl font-bold mb-6">Latest Posts</h1>
54+
<PostList url='https://jsonplaceholder.typicode.com/posts?_limit=10' />
55+
</div>
56+
);
57+
}
58+
59+

components/PostList/readme.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# PostList
2+
3+
## Overview
4+
5+
The **PostList** component fetches and displays a list of posts from an API endpoint. It shows a loading indicator while fetching and handles errors. Ideal for demonstrating async data fetching with React hooks and Tailwind CSS styling.
6+
7+
## Usage
8+
9+
| Prop | Type | Required | Default | Description |
10+
|------|--------|----------|-------------------------------------------------------------|---------------------------------|
11+
| `url` | string | No | https://jsonplaceholder.typicode.com/posts?_limit=5 | API endpoint to fetch posts from |
12+
13+
```jsx
14+
<PostList url="https://your.api.com/posts?limit=10" />

0 commit comments

Comments
 (0)