FrontendPro

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

  • loading is true while a request is in flight.
  • A non-2xx response sets error to an Error whose message contains the status code, for example "HTTP 500".
  • When url changes, abort the previous request with an AbortController, and never show data from an older URL.
  • Abort the request when the component unmounts.
  • An aborted request must not set error.
  • url === null means "do not fetch": loading is false and 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.

All 150 answersOne payment, yours forever