@@ -29,3 +29,40 @@ export function useMutationWithToast() {
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface RunToastMutationOptions<T> {
|
||||
error: string;
|
||||
success?: string;
|
||||
onSuccess?: (response: T) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Imperative sibling of `useMutationWithToast` for flows that must `await` a result (e.g. keep an
|
||||
* editor open on failure). Runs the action, treats non-2xx as failure, toasts accordingly, and
|
||||
* resolves to `true` only on success.
|
||||
*/
|
||||
export function useToastMutation() {
|
||||
const { showInfo, showError } = useToasts();
|
||||
|
||||
return async function runWithToast<T extends ApiResponseLike>(
|
||||
action: () => Promise<T>,
|
||||
{ error, success, onSuccess }: RunToastMutationOptions<T>
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const response = await action();
|
||||
const message = getResponseError(response);
|
||||
if (message) {
|
||||
showError(`${error}: ${message}`);
|
||||
return false;
|
||||
}
|
||||
onSuccess?.(response);
|
||||
if (success) {
|
||||
showInfo(success);
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(`${error}: ${getErrorMessage(err)}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user