50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import { router } from '@inertiajs/vue3';
|
|
import { computed, ref, type Ref } from 'vue';
|
|
import { toast } from 'vue-sonner';
|
|
|
|
interface UseDestroyOptions {
|
|
url: string | Ref<string>;
|
|
preserveScroll?: boolean;
|
|
errorMessage?: string;
|
|
onSuccess?: () => void;
|
|
onError?: (errors: Record<string, string>) => string | void;
|
|
}
|
|
|
|
export function useDestroy({ url, preserveScroll = true, errorMessage, onSuccess, onError }: UseDestroyOptions) {
|
|
const open = ref(false);
|
|
const processing = ref(false);
|
|
const resolvedUrl = computed(() => (typeof url === 'string' ? url : url.value));
|
|
|
|
function destroy() {
|
|
processing.value = true;
|
|
|
|
router.delete(resolvedUrl.value, {
|
|
preserveScroll,
|
|
onSuccess: () => {
|
|
open.value = false;
|
|
onSuccess?.();
|
|
},
|
|
onError: (errors) => {
|
|
if (onError) {
|
|
const result = onError(errors);
|
|
|
|
if (typeof result === 'string') {
|
|
toast.error(result);
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (errorMessage) {
|
|
toast.error(errorMessage);
|
|
}
|
|
},
|
|
onFinish: () => {
|
|
processing.value = false;
|
|
},
|
|
});
|
|
}
|
|
|
|
return { open, processing, destroy };
|
|
}
|