Version 3 is just around the corner and the composition API is bringing some new exciting possibilities, like building React Hook-like functions to help manage and share common logic and functionality
One of the cases where we might take advantage of hooks — and that seems to be in the spotlights theses days — is the use of SWR, Stale While Revalidate. It’s a strategy that to keep the balance between immediacy — loading cached content right away — and freshness — ensuring updates to the cached content.
Modern browsers these days already have support to use this feature on the fly, but for this, the API must send specific headers in the response. You can learn more about this approach in this article.
The problem with this approach is that sometimes you use someone else’s APIs, and changing response headers is not a viable option. To solve this, we will build our own custom hook that can be re-used across all your components.
So let’s get our hands dirty and build a simple solution to this.
To start let’s define what we’ll be doing. I’ve made a simple flowchart to explain how this hook will work:
We’ll receive a key to identify the request and the promise to be resolved. Then we check if the key already exists in the cache. If so, we inform the caller of the cached value. Then we resolve the promise (if we have the cached result or not) and inform the caller the result: If it’s a success we update the cache and inform the caller of the updated value, otherwise, we inform the caller we had an error resolving the promise.
You might ask why it’s a promise and not the URL of the API that we’re calling. By using a promise as input and not the URL we’re giving the option for this hook to be used in any case the result depends on a promise, whether it’s an API call or not. And even if it will be used only for API calls, we’ll keep the caller’s right to choose which approach will be used: The native fetch API, Axios, jquery’s AJAX , Angular’s $http or any other amongst the many solutions available on the internet.
#vuejs #vue #vue-3 #programming #javascript