Browser and frontend
From frontend to API: fetch, JSON and state
Showing the loading, success, empty and error states of a data request correctly.
Understand the concept
Code running in the browser uses fetch for data. fetch returns a Promise that rejects on network failure but not on HTTP errors such as 404 or 500; checking response.ok is your job. The body arrives as a stream and is parsed with response.json().
Every data request has at least four states: loading, success, empty and error. Designing only the success state is the most common gap. Loading can be shown with a skeleton shaped like the final content; the error state should tell the user what they can do (retry).
When a user clicks quickly, an old request’s response can arrive after a newer one and overwrite the screen with stale data. AbortController cancels the previous request. This site’s blog search and pagination cancel earlier requests for this reason and keep the previous results instead of clearing them when the API fails.
How the interface behaves on a slow or failing network is the real measure of quality.
Assuming fetch throws on a 500 response and skipping the response.ok check.
One topic. Three levels of depth.
const res = await fetch("/api/blog?page=2");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();HTTP errors do not reject fetch; the check is explicit.
This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.
Try it yourself first.
‘sq’ and then ‘sql’ are typed quickly into a search box. The ‘sq’ response arrives later and wrong results stay on screen. What do you change?
Show the solution and explanation
Her yeni aramada önceki isteği AbortController ile iptal et
(veya yanıtı, istek anındaki sorguyla eşleşmiyorsa yok say).
İsteğe bağlı: 250 ms debounce.Responses do not arrive in request order. Only the latest request’s result should reach the screen.