import { useEffect, useState } from 'react';
import './App.css';
import { type Book } from './Book';
import BookForm from './BookForm';

const App: React.FC = () => {
  const [books, setBooks] = useState<Book[]>([]);

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const response = await fetch('http://localhost:3001/books');
    const data: Book[] = await response.json();
    setBooks(data);
  }

  async function handleSubmit(formData: FormData) {
    await fetch('http://localhost:3001/books', {
      method: 'POST',
      body: formData,
    });
    fetchData();
  }

  return (
    <div>
      <BookForm onSave={handleSubmit} />
      <hr />
      <ul>
        {books.map((book) => (
          <li key={book.id}>
            {book.title}
            {book.image && (
              <img src={book.image} height="40" width="40" alt={book.title} />
            )}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

