Skip to content

Instantly share code, notes, and snippets.

@kevinxh
Last active December 10, 2020 22:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinxh/d06a7248a2d64ac23d7ffbd50dea8d76 to your computer and use it in GitHub Desktop.
Save kevinxh/d06a7248a2d64ac23d7ffbd50dea8d76 to your computer and use it in GitHub Desktop.
Caching mechanism to avoid duplicate requests #pattern

How to avoid sending duplicate requests?

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
    }

How does it work?

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment