Lesson 8 of 8
Caching requests
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
One request per ID
Explanation
If five components on a page ask for the same user's data, five identical requests go to the server. A simple cache turns them into one: a Map that links each ID to its request.
The trap is in what you store. If you store the result after await, every call that comes in at the same moment finds the cache empty, so they all send their requests at once. Instead, store the promise itself the moment you send the request, and every caller after that shares that same request, even while it's still in flight.
Storing the promise has a price, because a rejected promise stays rejected. If the request fails, remove it from the cache, or the user stays stuck on the error until they reload the page.
Your task
Make getUser(id) fetch each ID from the network only once, even when it's called for that ID several times at the same moment, and remove the ID from the cache if its request fails.
Checks
5 checks- getUser returns the requested user
- A repeated call gets its result from the cache
- Calls made at the same moment share one request
- Each ID gets its own request and result
- A failed request doesn't stay in the cache