VUE

useFetch Composable

A simple data fetching composable with loading state and error handling

Vue3ComposablesFetch

Code

import { ref, type Ref } from 'vue';

interface UseFetchReturn<T> {
  data: Ref<T | null>;
  loading: Ref<boolean>;
  error: Ref<Error | null>;
  execute: () => Promise<void>;
}

export function useFetch<T>(url: string): UseFetchReturn<T> {
  const data = ref<T | null>(null) as Ref<T | null>;
  const loading = ref(false);
  const error = ref<Error | null>(null);

  const execute = __TOKEN_16__ () => {
    loading.value = true;
    error.value = null;
    
    try {
      const response = await fetch(url);
      __TOKEN_20__ (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      data.value = await response.json();
    } __TOKEN_24__ (e) {
      error.value = e instanceof Error ? e : new Error('Unknown error');
    } finally {
      loading.value = false;
    }
  };

  return { data, loading, error, execute };
}

// Usage example
// const { data, loading, error, execute } = useFetch<User[]>('/api/users');
// onMounted(() => execute());