Skip to content
Middle+5 views

Implement a React component that fetches a list of users from JSONPlaceholder, displays “Loading...” while loading, and shows the users in a table with ID, Name, Phone, and Company columns. Add sorting if time permits.

Practice

Asked at

AI answer

import { useEffect, useMemo, useState } from "react";

type User = {
  id: number;
  name: string;
  phone: string;
  company: { name: string };
};
type SortKey = "id" | "name" | "phone" | "company";

export default function UsersTable() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sortKey, setSortKey] = useState<SortKey>("id");
  const [ascending, setAscending] = useState(true);

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

    fetch("https://jsonplaceholder.typicode.com/users", {
      signal: controller.signal,
    })
      .then((response) => {
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json() as Promise<User[]>;
      })
      .then(setUsers)
      .catch((err: unknown) => {
        if (!controller.signal.aborted) {
          setError(err instanceof Error ? err.message : "Failed to load data");
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });

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

  const sortedUsers = useMemo(() => {
    return [...users].sort((a, b) => {
      const left = sortKey === "company" ? a.company.name : a[sortKey];
      const right = sortKey === "company" ? b.company.name : b[sortKey];
      const comparison =
        typeof left === "number" && typeof right === "number"
          ? left - right
          : String(left).localeCompare(String(right), undefined, {
              numeric: true,
              sensitivity: "base",
            });
      return ascending ? comparison : -comparison;
    });
  }, [users, sortKey, ascending]);

  function sortBy(key: SortKey) {
    if (sortKey === key) setAscending((value) => !value);
    else {
      setSortKey(key);
      setAscending(true);
    }
  }

  if (loading) return <p>Loading...</p>;
  if (error) return <p role="alert">Loading error: {error}</p>;

  const columns: { key: SortKey; label: string }[] = [
    { key: "id", label: "ID" },
    { key: "name", label: "Name" },
    { key: "phone", label: "Phone" },
    { key: "company", label: "Company" },
  ];

  return (
    <table>
      <thead>
        <tr>
          {columns.map(({ key, label }) => (
            <th key={key}>
              <button type="button" onClick={() => sortBy(key)}>
                {label}{sortKey === key ? (ascending ? " ▲" : " ▼") : ""}
              </button>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sortedUsers.map((user) => (
          <tr key={user.id}>
            <td>{user.id}</td>
            <td>{user.name}</td>
            <td>{user.phone}</td>
            <td>{user.company.name}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

AbortController cancels the request when the component unmounts; sorting creates a copy of the array without modifying the original state.