Fix the Data Fetching Race Condition

Medium
Free
#Data Fetching

The component below fetches a user's profile whenever a different user is selected. It has a subtle but very common bug: if you switch users quickly, an earlier (slower) request can resolve after a later one and overwrite the correct data with stale data. Fix the effect so the UI always reflects the most recently selected user, regardless of the order in which the network responses arrive. The simulated fetchUser function intentionally responds slower for user 1 than for the others so the race is reproducible.

Requirements

  • Selecting a user must fetch that user's profile via the provided fetchUser function inside an effect.
  • The element with data-testid="current-user" must always display the most recently selected user's name, even when an earlier request resolves later.
  • Ignore stale responses using an effect cleanup flag (an ignore boolean) or an AbortController — do not call setState for a request that is no longer current.
  • Do not change the fetchUser function or the button markup.

Concepts you'll practice