import React, { useEffect, useState } from 'react';
import Heading from '../../components/heading';

const ListPage = (): React.ReactElement => {
  const [error, setError] = useState<string>(null);
  const [data, setData] = useState<Array<{ id: number; title: string; description: string }>>();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const handle = async () => {
      setIsLoading(true);
      try {
        const res = await fetch('/api/list');
        const data = await res.json();
        if (res.ok) {
          setData(data);
        } else {
          setError(data.message);
        }
      } catch (e) {
        setError(e.message);
      } finally {
        setIsLoading(false);
      }
    };
    handle();
  }, []);

  return (
    <>
      <Heading>List Page New</Heading>
      {isLoading && <div>Loading...</div>}
      {error && <div>Произошла ошибка</div>}
      {data?.map((item) => {
        return (
          <div key={item.id}>
            {item.id}: {item.title} - {item.description}
          </div>
        );
      })}
    </>
  );
};

export default ListPage;
