Coding exercise: fetch API data and display it in a table in React.

React practical coding · Freshers

Model answer

Track three states: loading, error and data. Fetch in an effect, cancel on unmount, and check response.ok because fetch does not throw on a 404 or 500.

function UsersTable() {
  const [rows, setRows] = useState([]);
  const [state, setState] = useState('loading');
  useEffect(() => {
    const ctrl = new AbortController();
    fetch('https://jsonplaceholder.typicode.com/users', { signal: ctrl.signal })
      .then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then((d) => { setRows(d); setState('ok'); })
      .catch((e) => { if (e.name !== 'AbortError') setState('error'); });
    return () => ctrl.abort();
  }, []);
  if (state === 'loading') return <p>Loading…</p>;
  if (state === 'error') return <p role="alert">Could not load users.</p>;
  return (
    <table>
      <thead><tr><th>Name</th><th>Email</th><th>City</th></tr></thead>
      <tbody>{rows.map((u) => (
        <tr key={u.id}><td>{u.name}</td><td>{u.email}</td><td>{u.address.city}</td></tr>))}</tbody>
    </table>
  );
}

In a real project a library such as TanStack Query handles caching, retries and loading states for you. Mention it, but be ready to write the plain version.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

React.js Full Course: Beginner to Advanced .

Sign in to add your own answer.

More questions