// 2 variant try-catch, await

import { useEffect, useState } from "react";
import User from "./User";

export default function App() {
  const [users, setUsers] = useState([]);
  const [status, setStatus] = useState("idle");

  useEffect(() => {
    const controller = new AbortController();
    (async () => {
      try {
        setStatus("loading");
        setUsers([]);
        const res = await fetch("https://jsonplaceholder.typicode.com/users", {
          signal: controller.signal,
        });
        if (res.ok) {
          setUsers(await res.json());
          setStatus("fetched");
          return;
        }
        throw new Error("Error fetching users");
      } catch (e) {
        if (e.name === "AbortError") return;
        setStatus("error");
        setUsers([]);
        console.log(e.message);
      }
    })();

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

  return (
    <>
      <h1>Users List</h1>
      {status === "loading" && <h2>Loading...</h2>}
      {status === "error" && <h2>Error!</h2>}
      {status === "fetched" && users.length === 0 && <p>No users found.</p>}
      {status === "fetched" && <User users={users} />}
    </>
  );
}