gitGood.dev
← Back to problems

Frontend: useFetch Custom Hook (Loading/Error/Data State Machine)

MediumTypeScript

Description

> This problem is paper-only - see explanation for the canonical React solution. A reusable `useFetch(url)` hook returns `{ data, error, status }` where status is one of `"idle" | "loading" | "success" | "error"`. The auto-grader validates the state-transition rules: - Initial: `{ data:null, error:null, status:"idle" }`. - On request start (`{ type: "start" }`): status -> `"loading"`, clear error, **keep stale data** (better UX during refetch). - On success (`{ type: "success", payload }`): `{ data: payload, error: null, status: "success" }`. - On error (`{ type: "error", error: e }`): `{ data: prev.data, error: e, status: "error" }` - keep stale data so the UI can show "stale + retry". **For the auto-grader:** implement the pure reducer `fetchReducer(state, action)`.
Example 1
Input: state = {data:null,error:null,status:"idle"}, action = {type:"start"}
Output: {data:null,error:null,status:"loading"}
Example 2
Input: state = {data:[1],error:null,status:"success"}, action = {type:"start"}
Output: {data:[1],error:null,status:"loading"}
Explanation: Stale data preserved during refetch.

Constraints

- action.type is "start" | "success" | "error"
Loading editor...