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

type Props = {
  children: (books: Book[], error: string | null) => React.ReactNode;
};

const BooksLoader: React.FC<Props> = ({ children }) => {
  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 children(books, error);
};

export default BooksLoader;
