summaryrefslogtreecommitdiff
path: root/react/08-auth-with-context/src/features/posts/components/PostList.jsx
blob: a7ccd3b8bb06b1d897058f15054776deee944a58 (plain)
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
import { useState, useEffect } from 'react'
import api from '../../../services/api'

const PostList = () => {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // Fetch data on component mount
    useEffect(() => {
        api
            .get("/posts") // Replace with your actual API endpoint
            .then((response) => {
                setPosts(response.data);
                setLoading(false);
            })
            .catch((err) => {
                setError(err.message);
                setLoading(false);
            });
    }, []);

    if (loading) return <p>Loading posts...</p>;
    if (error) return <p style={{ color: "red" }}>Error: {error}</p>;

    return (
        <div style={{ padding: "10px", fontFamily: "sans-serif" }}>
            <h3>Latest posts</h3>

            {/* 1. LIST VIEW */}
            <ul>
                {posts.map((post) => (
                    <li key={post.id}>
                        <strong>{post.title}</strong> by {post.author} (ID: {post.id})
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default PostList