tezvyn:

Fetching REST Data with Loading and Error State

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

data fetching with state.

OUTLINE

track loading, data, and error; fetch in an effect, check response.ok, parse JSON, handle catch and finally.

RED FLAG

ignoring non-2xx responses or leaving loading true on error.

WHAT THIS TESTS Whether you handle the complete async lifecycle, including the subtle fetch behavior on HTTP errors and cleanup.

A GOOD ANSWER COVERS Maintain three state values: a boolean loading, the data, and an error. In a useEffect that runs on mount, set loading true, call fetch with await, and then crucially check response.ok, because the fetch promise only rejects on network failure, not on HTTP status codes like 404 or 500; throw or set an error when not ok. If ok, await response.json and store the parsed data. Wrap the whole thing in try/catch so network failures populate error, and use finally to set loading false regardless of outcome so the UI never hangs. In render, show a loading indicator while loading is true, an error message if error is set, and the data otherwise. Guard against updating state after unmount using an AbortController or an isMounted flag to avoid the warning and wasted work if the user navigates away mid-request.

COMMON WRONG ANSWERS Assuming fetch rejects on a 404 or 500, so error handling never catches server errors. Forgetting finally, leaving loading stuck true when an error throws. Not handling the empty or error UI states. Setting state after the component unmounts.

LIKELY FOLLOW-UPS Why fetch does not reject on HTTP error status. How AbortController cancels the request on unmount. When to reach for a library like React Query instead of hand-rolling this.

ONE CONCRETE EXAMPLE A component sets loading true, fetches /api/users, checks response.ok and throws on failure, parses JSON into data, catches errors into error, and sets loading false in finally. The render returns an ActivityIndicator while loading, a retry message on error, and a FlatList of users on success.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.