import { onMounted, ref, type Ref } from "vue"; import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon"; export interface ISimpleDataLoader extends ILoaderCommon

{ content: Ref; getLastParams: () => P | undefined; } export function useSimpleDataLoader( loader: (params?: P) => Promise, loadWhenMounted = true, emptyIfArrayEmpty = true, ) : ISimpleDataLoader { const content = ref(null) as Ref; const loadStatus = ref('loading'); const loadError = ref(''); let lastParams: P | undefined; async function loadData(params?: P) { if (params) lastParams = params; loadStatus.value = 'loading'; try { const res = (await loader(params ?? lastParams)) as T; content.value = res; if (Array.isArray(res) && emptyIfArrayEmpty && (res as any[]).length === 0) loadStatus.value = 'nomore'; else loadStatus.value = 'finished'; loadError.value = ''; } catch(e) { loadError.value = '' + e; loadStatus.value = 'error'; console.log(e); } } onMounted(() => { if (loadWhenMounted) { setTimeout(() => { loadData(); }, (0.5 + Math.random()) * 500); } }) return { content, loadStatus, loadError, loadData, getLastParams: () => lastParams, } }