forked from rajun/ar-test
feat: add hook to toast action results
This commit is contained in:
parent
d8e557dff9
commit
b16bfa74b9
22
app/hooks/use-action-toast.ts
Normal file
22
app/hooks/use-action-toast.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import type { ActionResult } from '~/types/action';
|
||||
|
||||
// Toasts every new action result once; `onSuccess` runs for successful ones
|
||||
export function useActionToast<Intent extends string>(
|
||||
result: ActionResult<Intent> | undefined,
|
||||
onSuccess?: (result: Extract<ActionResult<Intent>, { ok: true }>) => void,
|
||||
) {
|
||||
const onSuccessRef = useRef(onSuccess);
|
||||
onSuccessRef.current = onSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (!result) return;
|
||||
if (result.ok) {
|
||||
toast.success(result.message);
|
||||
onSuccessRef.current?.(result);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
}, [result]);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user