It is common to see the client side sending duplicate fetch data requests to an API endpoint or desktop page.
To avoid sending duplicate requests, I recommend to implement a caching function that caches HTTP responses.
Example:
// WARNING: this is sudo code, test before use!
const promiseCache = {}
fetchData(url) {
// if we have requested the same url previously
// just resolve it from the cache instead of sending duplicate requests
const promise = promiseCache[path] ?
Promise.resolve(promiseCache[path]) :
fetch(path)
.then((res) => /* processing */)
promiseCache[path] = promise
return promise
}
If there are multiple requests send to the same endpoint, the method will return the cached HTTP response.
If needed, you can add functionalities such as:
- add option parameter to forceFetch (never use cache)
- cache requests ignoring query parameters