I'm working on a TypeScript-first fetch wrapper that now has automatic request deduplication. The idea is to ensure that if multiple identical requests are made, only one network call occurs and all the callers share the same result. I use a Map to track these requests with a deduplication key. For every deduplicated request, I hold onto the promise and its resolve/reject functions, allowing multiple concurrent calls to be resolved together. I also handle various body types carefully, but I'm interested in knowing if there's a better approach or any edge cases I might have overlooked. What would you suggest for implementing this kind of feature? Are there better patterns I could employ?
3 Answers
If you're keen to see how other libraries tackle this, check out Tanstack Query or SWR. They both handle request deduplication in interesting ways which could give you some good ideas. Here's a link to one of their discussions that might be helpful: [Tanstack Query Discussions](https://github.com/TanStack/query/discussions/608#discussioncomment-29735).
In practice, request deduplication can really save you from making redundant requests, especially if you're working with frameworks like React where multiple components might trigger the same network call. I think having a short cache mechanism could also help with this, but it might be less complex to implement than full deduplication. Just remember that if you're polling or have components that fire off requests rapidly, deduplication can prevent numerous calls before a response comes back.
I usually believe that deduplication should be handled at the API level instead of within the client. If multiple parts of your app need the same data, consider using a centralized service for data fetching. It keeps the architecture cleaner and you're not reinventing the wheel by managing multiple identical requests.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically