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

const BooksListContainer: React.FC = () => {
  const [books, setBooks] = useState<Book[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const response = await fetch(
          `${import.meta.env.VITE_API_SERVER}/books`
        );
        if (!response.ok) {
          throw new Error('Anfrage fehlgeschlagen');
        }
        const data = await response.json();
        setBooks(data);
      } catch (error) {
        console.error(error);
        setError('Es ist ein Fehler aufgetreten');
      }
    })();
  }, []);

  return <BooksList books={books} error={error} />;
};

export default BooksListContainer;
