chore: add handler parent
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
// Reusable async handler for CRUD actions with toast and state management
|
||||
export type ToastFn = (params: { title: string; description: string; variant: 'default' | 'destructive' }) => void
|
||||
|
||||
export interface HandleAsyncActionOptions<T extends any[], R> {
|
||||
action: (...args: T) => Promise<R & { success: boolean }>
|
||||
args?: T
|
||||
toast: ToastFn
|
||||
successMessage: string
|
||||
errorMessage: string
|
||||
onSuccess?: (result: R) => void
|
||||
onError?: (error: unknown) => void
|
||||
onFinally?: (isSuccess: boolean) => void
|
||||
}
|
||||
|
||||
export async function handleAsyncAction<T extends any[], R>({
|
||||
action,
|
||||
args = [] as unknown as T,
|
||||
toast,
|
||||
successMessage,
|
||||
errorMessage,
|
||||
onSuccess,
|
||||
onError,
|
||||
onFinally,
|
||||
}: HandleAsyncActionOptions<T, R>) {
|
||||
let isSuccess = false
|
||||
try {
|
||||
const result = await action(...args)
|
||||
if (result.success) {
|
||||
toast({ title: 'Berhasil', description: successMessage, variant: 'default' })
|
||||
isSuccess = true
|
||||
if (onSuccess) onSuccess(result)
|
||||
} else {
|
||||
toast({ title: 'Gagal', description: errorMessage, variant: 'destructive' })
|
||||
if (onError) onError(result)
|
||||
}
|
||||
} catch (error) {
|
||||
toast({ title: 'Gagal', description: errorMessage, variant: 'destructive' })
|
||||
if (onError) onError(error)
|
||||
} finally {
|
||||
if (onFinally) onFinally(isSuccess)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user