diff --git a/src/composables/useAsync.ts b/src/composables/useAsync.ts new file mode 100644 index 00000000..9fe25eed --- /dev/null +++ b/src/composables/useAsync.ts @@ -0,0 +1,25 @@ +import { useAsyncState } from "@vueuse/core"; +import axios from "axios"; +import { computed } from "vue"; + +export function useAsync(promise: Promise | ((...args: any[]) => Promise)) { + const { state, isLoading, execute, error } = useAsyncState(promise, null, { + immediate: false, + }); + + const errorMsg = computed(() => { + if (!error.value) return null; + else if (axios.isAxiosError(error.value) && error.value.response?.data?.message) { + return error.value.response.data.message; + } else { + return "Unknown error occurred :("; + } + }); + + return { + state, + isLoading, + execute, + errorMsg, + }; +} diff --git a/src/pages/admin.vue b/src/pages/admin.vue index bb4f147d..1589df44 100644 --- a/src/pages/admin.vue +++ b/src/pages/admin.vue @@ -8,6 +8,7 @@ import { useAxios } from "@vueuse/integrations/useAxios"; import axios from "axios"; import { computed, ref, watchEffect } from "vue"; import { useRoute, useRouter } from "vue-router"; +import { useAsync } from "@/composables/useAsync"; const route = useRoute(); const router = useRouter(); @@ -28,7 +29,7 @@ const { data: users, error: fetchError, isLoading: fetchLoading, - execute, + execute: fetchUsers, } = useAxios("/user", fetcher); const searchName = ref(""); const searchRole = ref(null); @@ -39,8 +40,6 @@ const filteredUsers = computed(() => ); const edittingUsername = ref(""); -const isLoading = ref(false); -const errorMsg = ref(""); const initialUserForm = { displayedName: "", role: 0, @@ -63,26 +62,21 @@ function editUser(username: string) { }; edittingUsername.value = username; } + +const { + isLoading, + errorMsg, + execute: modifyUser, +} = useAsync(async () => { + if (!userForm.value.password) userForm.value.password = null; + await api.User.modify(edittingUsername.value, { ...userForm.value }); + fetchUsers(); + userForm.value = { ...initialUserForm }; + edittingUsername.value = ""; +}); async function submit() { if (!(await v$.value.$validate())) return; - - isLoading.value = true; - try { - if (!userForm.value.password) userForm.value.password = null; - await api.User.modify(edittingUsername.value, { ...userForm.value }); - execute(); - userForm.value = { ...initialUserForm }; - edittingUsername.value = ""; - } catch (error) { - if (axios.isAxiosError(error) && error.response?.data?.message) { - errorMsg.value = error.response.data.message; - } else { - errorMsg.value = "Unknown error occurred :("; - } - throw error; - } finally { - isLoading.value = false; - } + modifyUser(); } @@ -135,7 +129,7 @@ async function submit() { {{ displayedName }} {{ ROLE[role] }} -
+