Skip to content

Instantly share code, notes, and snippets.

@Rlesjak
Created July 17, 2022 14:53
Show Gist options
  • Save Rlesjak/3f3992921c8dfebb50223dc482fceeeb to your computer and use it in GitHub Desktop.
Save Rlesjak/3f3992921c8dfebb50223dc482fceeeb to your computer and use it in GitHub Desktop.
Simple cached fetch in Vue3 with composable functions.
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