Skip to content

Instantly share code, notes, and snippets.

@yann-yinn
Created January 28, 2022 11:01
Show Gist options
  • Save yann-yinn/aa12f9f7a70e28fbd3e3f62c1abbdb4e to your computer and use it in GitHub Desktop.
Save yann-yinn/aa12f9f7a70e28fbd3e3f62c1abbdb4e to your computer and use it in GitHub Desktop.
useApiRequest - a small Vue 3 composable to fetch data from a JSON API
/**
* Usage in a component:
*
* import useApiRequest from "@/composables/useApiRequest"
*
* const saveRequest = useApiRequest("https://jsonplaceholder.typicode.com/userse");
* function handleFormSubmit() {
* saveRequest.execute()
* }
*/
import { reactive } from "vue";
export default function apiRequest<Type>(url: string) {
const state = reactive<{
pending: boolean;
data: Type | null;
error: string | null;
}>({
pending: false,
data: null,
error: null,
});
async function execute(): Promise<Type> {
state.pending = true;
state.error = null;
const response = await fetch(url);
if (!response.ok) {
state.error = `Error ${response.status}`;
state.pending = false;
throw new Error(state.error);
}
const data = await response.json();
state.data = data;
state.pending = false;
return data;
}
return { state, execute };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment