wasAsked.

If an API returns an array of employees, how would you display it in a table?

Capgemini · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

Typical approach: fetch the data in a service, expose it to the component, and render it with a table, handling loading, empty and error states. Here is an Angular version (with a React version below). Angular // employee.service.ts export interface Employee { id: number; name: string; department: string; salary: number; } @Injectable({ providedIn: 'root' }) export class EmployeeService { private readonly http = inject(HttpClient); getAll() { return this.http.get<Employee[]>('/api/employees'); } } // employee-table.component.ts @Component({ selector: 'app-employee-table', imports: [AsyncPipe, CurrencyPipe], template: ` @if (employees$ | async; as employees) { @if (employees.length === 0) { <p>No employees found.</p> } @else { <table> <caption>Employees</caption> <thead> <tr><th scope="col">Name</th><th scope="col">Department</th><th scope="col">Salary</th></tr> </thead> <tbody> @for (e of employees; track e.id) { <tr><td>{{ e.name }}</td><td>{{ e.department }}</td><td>{{ e.salary | currency:'INR' }}</td></tr> } </tbody> </table> } } @else { <p>Loading…</p> } ` }) export class EmployeeTableComponent { employees$ = inject(EmployeeService).getAll().pipe( catchError(() => { this.error = 'Could not load employees.'; return of([] as Employee[]); }) ); error = ''; } React function EmployeeTable() { const [employees, setEmployees] = useState<Employee[] | null>(null); const [error, setError] = useState(''); useEffect(() => { const ctrl = new AbortController(); fetch('/api/employees', { signal: ctrl.signal }) .then(r => { if (!r.ok) throw new Error(); return r.json(); }) .then(setEmployees) .catch(e => { if (e.name !== 'AbortError') setError('Could not load employees.'); }); return () => ctrl.abort(); }, []); if (error) return <p role="alert">{error}</p>; if (!employees) return <p>Loading…</p>; if (employees.length === 0) return <p>No employees found.</p>; return ( <table> <thead><tr><th>Name</th><th>Department</th><th>Salary</th></tr></thead> <tbody> {employees.map(e => ( <tr key={e.id}><td>{e.name}</td><td>{e.department}</td><td>{e.salary.toLocaleString('en-IN', { style: 'currency', currency: 'INR' })}</td></tr> ))} </tbody> </table> ); } Points to mention - Use a stable key (track e.id or key={e.id}) so rows are updated efficiently. - Semantic, accessible table markup: <caption>, <th scope="col">. - Handle loading, empty and error states. - For large datasets: server-side pagination, sorting and filtering, or virtual scrolling; or a table library (Angular Material table, AG Grid, TanStack Table). - Format values (currency and dates) with pipes or Intl APIs, and avoid computing values in templates on every render.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics