61Implement useFetch() with loading, error, and cancellation
mediumAbout 35 minutesCodingreacthooksfetchabortcontroller
Problem
Implement useFetch(url). It fetches JSON from url and returns { data, error, loading, refetch }.
function Profile({ id }) {
const { data, error, loading } = useFetch(`/api/users/${id}`);
if (loading) return <Spinner />;
if (error) return <p>Could not load: {error.message}</p>;
return <h1>{data.name}</h1>;
}Requirements
loadingistruewhile a request is in flight.- A non-2xx response sets
errorto anErrorwhose message contains the status code, for example"HTTP 500". - When
urlchanges, abort the previous request with anAbortController, and never show data from an older URL. - Abort the request when the component unmounts.
- An aborted request must not set
error. url === nullmeans "do not fetch":loadingisfalseand nothing is requested.refetch()runs the request again for the current URL.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
Keep data, error and loading in state, plus a reloadCount that refetch increments to re-run the effect.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.