Skip to content

Instantly share code, notes, and snippets.

@josueayala27
Last active December 27, 2024 14:09
Show Gist options
  • Select an option

  • Save josueayala27/4deb8fd83457fa36a82ce27008fecafd to your computer and use it in GitHub Desktop.

Select an option

Save josueayala27/4deb8fd83457fa36a82ce27008fecafd to your computer and use it in GitHub Desktop.
useApi.ts is a Vue.js composable that provides a simple interface for interacting with an API. This composable encapsulates the logic of making HTTP requests, handling responses, errors, and loading states, and conveniently provides the API data for use in Vue components.
import type { FetchOptions } from 'ohmyfetch';
import { useApiMethod } from '@/enums/composables/useApi';
/**
* Custom hook that makes an HTTP request to the API endpoint.
*/
export async function useApi<T>(
path: string,
opts?: FetchOptions,
prefix = 'api',
version = 'v1'
): Promise<T> {
const config = useRuntimeConfig();
const baseURL: string = config.public.API_URL + `/${prefix}/${version}/`;
const credentials: RequestCredentials = 'include';
/**
* Makes an HTTP request to fetch the CSRF cookie from the API endpoint.
*/
if (opts?.method !== useApiMethod.GET) {
await $fetch.raw(`${config.public.API_URL}/sanctum/csrf-cookie`, {
method: useApiMethod.GET,
credentials,
});
}
const CSRF_COOKIE = 'XSRF-TOKEN';
const token = useCookie(CSRF_COOKIE).value;
const headers: any = {
Referer: `${config.public.APP_URL}/`,
'X-XSRF-TOKEN': token,
};
return $fetch<T>(path, {
baseURL,
credentials,
headers: {
...headers,
...(useRequestHeaders(['cookie', 'referer']) as HeadersInit),
},
...(opts && { ...opts }),
onResponseError: ({ response }) => {
console.error("Fetch Error", response._data?.message)
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment