React Dojo

Search

Search concepts, exercises and quizzes

practiceintermediate

Fetch with cancellation

Load user data when the id changes. The trick: if the user clicks quickly between several ids, the old response can arrive after the new one and overwrite the UI. Cancel with AbortController.


Objectives

  1. 1.useEffect that triggers a fetch every time userId changes
  2. 2.Create an AbortController and pass it to the fetch as { signal }
  3. 3.In the effect cleanup, call ctrl.abort()
  4. 4.Ignore the AbortError — it's expected when cancelling
  5. 5.Show loading..., error, or data depending on the state
  6. 6.The buttons change userId instantly, without waiting for the fetch
your code
Hint

The function returned from useEffect runs BEFORE the next setup, so aborting there cancels the race. The fetch rejects with AbortError — filter that case in the catch.

Related concepts

Was this helpful?
Sign in to give feedback