import { useEffect, useState } from 'react';

type Props = {
  searchString: string;
};

type Book = {
  id: number;
  title: string;
};

const BooksList: React.FC<Props> = ({ searchString }) => {
  const [books, setBooks] = useState<Book[]>([]);

  useEffect(() => {
    const controller = new AbortController();

    fetch(`http://localhost:3001/books?title_like=${searchString}`, {
      signal: controller.signal,
    })
      .then((response) => response.json())
      .then((data) => setBooks(data))
      .catch(() => {});

    return () => controller.abort();
  }, [searchString]);

  return (
    <ul>
      {books.map((book) => (
        <li key={book.id}>{book.title}</li>
      ))}
    </ul>
  );
};

export default BooksList;
