|
| 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 | + |
0 commit comments