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.
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.
Also asked at СБЕР
- Have you worked with useLayoutEffect and how does it differ from useEffect?
- [name] asked: why did you decide to change your job?
- What is Event Loop in JavaScript?
- What is Virtual DOM and how does it work in React?
- Please tell us about your experience: what tasks do you solve, what is your area of responsibility, what technologies have you worked with, and how are the team processes organized?
Similar questions
- Design a page that displays a list of cards fetched from a backend, with additional filters and search by name. How would you organize the components, data loading, and handling of potential issues?
- Practical task: Refactor the UsersPage component into a cleaner, more efficient React/TypeScript component. You may create and delete files, extract components, types, and hooks, and comment on your decisions as you work.
- How would you implement loading the cards: the request, loading/error states, retries, an empty list, and canceling the request when the component unmounts?
- Implement a React component that displays a list of users with search by name or email, sorting A–Z/Z–A, loading and empty states, and asynchronous data loading.
- Implement a basic custom useFetch composable for making requests. It should return the data, loading state, and error. Do not implement items 9–10 yet.