Vue Composable pro API dotazy

Vue.js 📄 useApi.ts

Univerzální Vue composable pro správu stavu API dotazů s automatickým error handlingem a loading stavy

Vue Composable pro API dotazy
import { ref, computed, readonly } from "vue"
import type { Ref } from "vue"

export interface ApiState<T> {
  data: Ref<T | null>
  loading: Ref<boolean>
  error: Ref<string | null>
}

export function useApi<T>() {
  const data = ref<T | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const isLoading = computed(() => loading.value)
  const hasError = computed(() => error.value !== null)
  const hasData = computed(() => data.value !== null)

  const execute = async (apiCall: () => Promise<T>): Promise<T | null> => {
    try {
      loading.value = true
      error.value = null
      
      const result = await apiCall()
      data.value = result
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Neznámá chyba"
      data.value = null
      return null
    } finally {
      loading.value = false
    }
  }

  const reset = () => {
    data.value = null
    loading.value = false
    error.value = null
  }

  return {
    data: readonly(data),
    loading: readonly(loading), 
    error: readonly(error),
    isLoading,
    hasError,
    hasData,
    execute,
    reset
  }
}

Informace o gistu

ID:#13
Jazyk:Vue.js
Soubor:useApi.ts
Vytvořeno:1. srpna 2025
Likes:0