Created
January 28, 2022 11:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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