Handling Loading States, Errors, and Empty Results in the UI
Explore how to handle loading states, errors, and empty results in a React frontend fetching data with Axios. Understand best practices for showing spinners, friendly error messages, and empty state components to improve user experience. Learn to encapsulate this logic using a custom useApi Hook for consistent and reusable UI state management.
We'll cover the following...
Earlier lessons fetched and displayed data, but assumed the happy path: the request succeeds and returns results. Real requests take time, sometimes fail, and sometimes return nothing. An app that ignores these cases shows a blank screen while loading, breaks on an error, or displays an empty list with no explanation, all of which feel broken to a user. Handling the three states is what separates a prototype from a polished product.
Note: This React code is for read-along. It builds on the Axios fetch pattern from earlier in the chapter, adding the state handling around it.
To make the states concrete, the next visual should show the three outcomes a single fetch can produce:
That starts with the request that is still in flight.
The loading state
Between starting a fetch and receiving a response, there is a gap. During it, the UI ...