Files
FlightsAPI/resources/js/Composables/useApiResource.ts
T
2026-06-21 16:53:39 +10:00

43 lines
1.2 KiB
TypeScript

import { ref, onMounted, onUnmounted, type Ref } from 'vue'
import axios from 'axios'
import { api } from '@/api'
interface UseApiResourceReturn<T> {
data: Ref<T | null>
loading: Ref<boolean>
error: Ref<string | null>
refresh: () => Promise<void>
}
export function useApiResource<T>(url: string, immediate = true): UseApiResourceReturn<T> {
const data = ref<T | null>(null) as Ref<T | null>
const loading = ref(true)
const error = ref<string | null>(null)
let controller = new AbortController()
async function refresh() {
controller.abort()
controller = new AbortController()
loading.value = true
error.value = null
try {
const response = await api.get<T>(url, { signal: controller.signal })
data.value = response.data
} catch (e) {
if (!axios.isCancel(e)) {
error.value = 'Failed to load data'
console.error(e)
}
} finally {
loading.value = false
}
}
if (immediate) onMounted(refresh)
onUnmounted(() => controller.abort())
return { data, loading, error, refresh }
}