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

const BooksList: React.FC = () => {
  const [error, setError] = useState(false);
  const [books, setBooks] = useState<Book[]>([]);

  useEffect(() => {
    fetch('books/')
      .then((response) => {
        if (!response.ok) {
          throw new Error();
        }
        return response.json();
      })
      .then((data) => setBooks(data))
      .catch(() => setError(true));
  }, []);

  if (error) {
    return <div data-testid="error">Es ist ein Fehler aufgetreten!</div>;
  } else {
    return (
      <ul>
        {books.map((book) => (
          <li key={book.id} data-testid="book">
            {book.title}
          </li>
        ))}
      </ul>
    );
  }
};

export default BooksList;
