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

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

  async function fetchData() {
    let data: Book[];
    if (navigator.onLine) {
      const response = await fetch('http://localhost:3001/books');
      data = await response.json();
      bookDatabase.books.clear();
      bookDatabase.books.bulkAdd(data);
    } else {
      data = await bookDatabase.books.toArray();
    }
    setBooks(data);
  }

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

  return (
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>ISBN</th>
        </tr>
      </thead>
      <tbody>
        {books.map((book) => (
          <tr key={book.id}>
            <td>{book.title}</td>
            <td>{book.isbn}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default List;
