Delivering Vue 3 useFetch with caching, deduplication, and abort
Here's a Vue 3 composable implementing caching, request deduplication, and abort-on-unmount with reference counting. The example shows two components fetching the same URL simultaneously, sharing the request and cache, and aborting fetches only when all subscribers unmount.
// src/useFetch.js
import { ref, onUnmounted } from 'vue'
const cache = new Map()
const pending = new Map()
let idCounter = 0
export default function useFetch(url, options = {}) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
const opts = options.requestOptions || {}
const immediate = options.immediate !== false
const cacheKey = JSON.stringify([url, opts])
const clientId = ++idCounter
function startRequest() {
if (!url) return
if (cache.has(cacheKey)) {
data.value = cache.get(cacheKey)
return
}
if (pending.has(cacheKey)) {
const entry = pending.get(cacheKey)
entry.subscribers.add(clientId)
loading.value = true
entry.promise
.then(res => {
data.value = res
error.value = null
})
.catch(err => {
error.value = err
})
.finally(() => {
loading.value = false
})
return
}
loading.value = true
const controller = new AbortController()
const subscribers = new Set([clientId])
const promise = fetch(url, { ...opts, signal: controller.signal })
.then(async res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`)
const json = await res.json()
cache.set(cacheKey, json)
return json
})
.finally(() => {
pending.delete(cacheKey)
})
pending.set(cacheKey, { promise, controller, subscribers })
promise
.then(res => {
data.value = res
error.value = null
})
.catch(err => {
if (err.name !== 'AbortError') {
error.value = err
}
})
.finally(() => {
loading.value = false
})
}
function abort() {
if (!pending.has(cacheKey)) return
const entry = pending.get(cacheKey)
entry.subscribers.delete(clientId)
if (entry.subscribers.size === 0) {
entry.controller.abort()
pending.delete(cacheKey)
}
}
onUnmounted(() => {
abort()
})
function reload() {
cache.delete(cacheKey)
startRequest()
}
if (immediate) {
startRequest()
}
return { data, error, loading, reload, abort }
}
<!-- src/App.vue -->
<template>
<div>
<h1>useFetch Demo</h1>
<div>
<button @click="reloadA">Reload A</button>
<button @click="reloadB">Reload B</button>
</div>
<div style="display:flex; gap: 2rem;">
<section>
<h2>Request A</h2>
<p v-if="loadingA">Loading...</p>
<p v-else-if="errorA">Error: {{ errorA.message }}</p>
<pre v-else>{{ JSON.stringify(dataA, null, 2) }}</pre>
</section>
<section>
<h2>Request B (same URL, deduplicated)</h2>
<p v-if="loadingB">Loading...</p>
<p v-else-if="errorB">Error: {{ errorB.message }}</p>
<pre v-else>{{ JSON.stringify(dataB, null, 2) }}</pre>
</section>
</div>
</div>
</template>
<script setup>
import useFetch from './useFetch'
const {
data: dataA,
error: errorA,
loading: loadingA,
reload: reloadA,
} = useFetch('https://jsonplaceholder.typicode.com/todos/1')
const {
data: dataB,
error: errorB,
loading: loadingB,
reload: reloadB,
} = useFetch('https://jsonplaceholder.typicode.com/todos/1')
</script>
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
This setup ensures that simultaneous fetches to the same URL share one network request (deduplicated), cached responses are reused instantly, and fetches abort only when all consumers unmount before completion. The example demonstrates two consumers fetching the same data concurrently with shared state.
Below is a minimal Vue 3 example (using the Composition API) that implements a useFetch composable with:
- Caching: Responses are cached by a computed key (URL + options).
- Request deduplication: Multiple calls with the same key share the same in-flight request.
- Abort on unmount: If a component using
useFetch unmounts, it unsubscribes; if no subscribers remain for that in-flight request, it aborts via AbortController.
You can adapt the project structure for Vite or Vue CLI. For brevity, only the essential files are shown.
src/useFetch.js
import { ref, onUnmounted } from 'vue'
/**
* Global caches and pending requests.
*/
const cache = new Map()
// pending: key -> { promise, controller, subscribers: Set<number> }
const pending = new Map()
let clientIdCounter = 0
/**
* useFetch composable
* @param {String} url - The fetch URL
* @param {Object} options - Options:
* - immediate (Boolean): fetch immediately on creation (default true)
* - requestOptions (Object): options passed to `fetch()`
* @returns {Object} { data, error, loading, reload, abort }
*/
export default function useFetch(url, options = {}) {
const {
immediate = true,
requestOptions = {},
} = options
const data = ref(null)
const error = ref(null)
const loading = ref(false)
// Unique id for this consumer
const clientId = ++clientIdCounter
// Key to identify/cache/dedup the request
const cacheKey = JSON.stringify([url, requestOptions])
/**
* Start or reuse a fetch request.
*/
const startRequest = () => {
if (!url) return
// 1) If cached, return immediately
if (cache.has(cacheKey)) {
data.value = cache.get(cacheKey)
return
}
// 2) If an identical request is pending, subscribe to it
if (pending.has(cacheKey)) {
const entry = pending.get(cacheKey)
entry.subscribers.add(clientId)
loading.value = true
entry.promise
.then((res) => {
data.value = res
error.value = null
})
.catch((err) => {
error.value = err
})
.finally(() => {
loading.value = false
})
return
}
// 3) Create a new request
loading.value = true
const controller = new AbortController()
const subscribers = new Set([clientId])
const promise = fetch(url, { ...requestOptions, signal: controller.signal })
.then(async (res) => {
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`)
}
const json = await res.json()
cache.set(cacheKey, json)
return json
})
.finally(() => {
// remove from pending when the request completes or fails
pending.delete(cacheKey)
})
pending.set(cacheKey, { promise, controller, subscribers })
promise
.then((res) => {
data.value = res
error.value = null
})
.catch((err) => {
if (err.name === 'AbortError') {
console.warn('Fetch aborted for', cacheKey)
} else {
error.value = err
}
})
.finally(() => {
loading.value = false
})
}
// Fetch immediately unless immediate=false
if (immediate) {
startRequest()
}
/**
* Abort/unsubscribe logic
*/
const unsubscribeOrAbort = () => {
if (!pending.has(cacheKey)) return
const entry = pending.get(cacheKey)
entry.subscribers.delete(clientId)
// If no one else is waiting, abort
if (entry.subscribers.size === 0) {
entry.controller.abort()
pending.delete(cacheKey)
}
}
// Abort/unsubscribe if component unmounts
onUnmounted(() => {
unsubscribeOrAbort()
})
/**
* Force a refetch, clearing cached data
*/
const reload = () => {
cache.delete(cacheKey)
startRequest()
}
/**
* Manual abort by consumer
*/
const abort = () => {
unsubscribeOrAbort()
}
return { data, error, loading, reload, abort }
}
src/App.vue
<template>
<div class="app">
<h1>useFetch Demo</h1>
<div class="controls">
<button @click="reloadA">Reload A</button>
<button @click="reloadB">Reload B</button>
</div>
<div class="columns">
<div class="column">
<h2>Request A</h2>
<p v-if="loadingA">Loading...</p>
<p v-else-if="errorA">Error: {{ errorA.message }}</p>
<pre v-else>{{ JSON.stringify(dataA, null, 2) }}</pre>
</div>
<div class="column">
<h2>Request B (same URL, dedup)</h2>
<p v-if="loadingB">Loading...</p>
<p v-else-if="errorB">Error: {{ errorB.message }}</p>
<pre v-else>{{ JSON.stringify(dataB, null, 2) }}</pre>
</div>
</div>
</div>
</template>
<script setup>
import useFetch from './useFetch'
// Both use the same URL: they’ll share the same in-flight request, and
// then read from cache. Each has its own reload/abort, etc.
const {
data: dataA,
error: errorA,
loading: loadingA,
reload: reloadA,
} = useFetch('https://jsonplaceholder.typicode.com/todos/1')
const {
data: dataB,
error: errorB,
loading: loadingB,
reload: reloadB,
} = useFetch('https://jsonplaceholder.typicode.com/todos/1')
</script>
<style>
.app {
font-family: sans-serif;
padding: 1rem;
}
.controls {
margin-bottom: 1rem;
}
.columns {
display: flex;
gap: 1rem;
}
.column {
flex: 1;
}
pre {
background: #f7f7f7;
padding: 0.5rem;
}
</style>
src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
How it works:
- When
useFetch(url) is called, it:
- Checks the cache. If present, returns cached data.
- If already fetching the same key, it subscribes to that request (deduplication).
- Otherwise, creates a new
fetch with its own AbortController.
- If the component unmounts, it unsubscribes from any pending request. If no subscribers remain, the request is aborted.
- The
reload function clears the cache for that key and starts a fresh request.
You can adapt this pattern to include more features (custom cache invalidation, TTL, reactivity to URL changes, etc.) as needed.