Source: posts/page.js

'use client'
import React, { useEffect, useState } from 'react'; // Import React

/**
 * Posts Component
 * 
 * This component fetches and displays a list of posts from a JSON mockup backend API.
 * 
 * @module Posts
 */

/**
 * Renders the Posts component.
 * 
 * @returns {JSX.Element} The JSX element representing the Posts component.
 */
function Posts() {
  // State to store posts and loading status

  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
 
  // Fetch posts from the backend API on component mount

  useEffect(() => {
    fetch('http://localhost:5000/posts')
      .then(response => response.json())
      .then(data => {
        setPosts(data);
        setIsLoading(false);
      });
  }, []);

  return (
    <div className="container mx-auto mt-8">
      <button onClick={() => window.history.back()} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 mb-4 rounded inline-block">Back</button>
      <h1 className="text-3xl font-bold mb-8">Posts</h1>
      {isLoading ? (
        <div className="flex items-center justify-center">
          <svg className="animate-spin h-8 w-8 text-blue-500 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A8.001 8.001 0 014 12H0c0 6.627 5.373 12 12 12v-4c-3.313 0-6.292-1.343-8.485-3.515l1.415-1.414zM12 4a8 8 0 018 8h4c0-6.627-5.373-12-12-12v4c3.313 0 6.292 1.343 8.485 3.515l-1.415 1.414A7.963 7.963 0 0112 4z"></path>
          </svg>
          <span className="text-xl text-blue-500">Loading...</span>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
          {posts.map(post => (
            <div key={post.id} className="bg-white shadow-lg rounded-lg overflow-hidden">
              <div className="px-6 py-4">
                <div className="font-bold text-xl mb-2">{post.title}</div>
                <p className="text-gray-700 text-base">{post.body}</p>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Posts;