Created
July 17, 2022 14:53
-
-
Save Rlesjak/3f3992921c8dfebb50223dc482fceeeb to your computer and use it in GitHub Desktop.
Simple cached fetch in Vue3 with composable functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { computed, reactive, ref } from "vue"; | |
export const useFetch = (url, config = {}) => { | |
const data = ref(null); | |
const error = ref(null); | |
const loading = ref(null); | |
const _fetch = async () => { | |
loading.value = true; | |
try | |
{ | |
const resp = await fetch(url, { ...config }); | |
data.value = await resp.json(); | |
} | |
catch (err) | |
{ | |
error.value = err; | |
} | |
finally | |
{ | |
loading.value = false; | |
} | |
} | |
!config.skip && _fetch(); | |
return { error, data, loading, _fetch } | |
} | |
const cacheMap = reactive(new Map()); | |
export const useFetchWithCache = (key, url, config) => { | |
const info = useFetch(url, { skip: true, ...config }); | |
const update = () => cacheMap.set(key, info.data.value); | |
const clear = () => cacheMap.set(key, undefined); | |
const myCachedfetch = async () => { | |
try | |
{ | |
await info._fetch() | |
update() | |
} | |
catch (err) | |
{ | |
clear() | |
} | |
} | |
const data = computed(() => cacheMap.get(key)); | |
if (data.value == null) myCachedfetch(); | |
else info.loading = false; | |
return { ...info, _fetch: myCachedfetch, data, clear } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment