π OpenHands: AI-Driven Development
feat(frontend): add mutateWithToast utility for standardized mutation toast handling (#12433)
Dreamdcc8217317bc
diff --git a/frontend/src/components/features/settings/api-keys-manager.tsx b/frontend/src/components/features/settings/api-keys-manager.tsxindex 143aed0671..94128b6e6d 100644--- a/frontend/src/components/features/settings/api-keys-manager.tsx+++ b/frontend/src/components/features/settings/api-keys-manager.tsx@@ -10,6 +10,7 @@ import {displayErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";+import { mutateWithToast } from "#/utils/mutate-with-toast";import { CreateApiKeyModal } from "./create-api-key-modal";import { DeleteApiKeyModal } from "./delete-api-key-modal";import { NewApiKeyModal } from "./new-api-key-modal";@@ -60,18 +61,10 @@ function LlmApiKeyManager({const { t } = useTranslation();const [showLlmApiKey, setShowLlmApiKey] = useState(false);- const handleRefreshLlmApiKey = () => {- refreshLlmApiKey.mutate(undefined, {- onSuccess: () => {- displaySuccessToast(- t(I18nKey.SETTINGS$API_KEY_REFRESHED, {- defaultValue: "API key refreshed successfully",- }),- );- },- onError: () => {- displayErrorToast(t(I18nKey.ERROR$GENERIC));- },+ const handleRefreshLlmApiKey = async () => {+ await mutateWithToast(refreshLlmApiKey, undefined, {+ success: t(I18nKey.SETTINGS$API_KEY_REFRESHED),+ error: t(I18nKey.ERROR$GENERIC),});};diff --git a/frontend/src/components/features/settings/create-api-key-modal.tsx b/frontend/src/components/features/settings/create-api-key-modal.tsxindex 4c4c0242d0..b933314aea 100644--- a/frontend/src/components/features/settings/create-api-key-modal.tsx+++ b/frontend/src/components/features/settings/create-api-key-modal.tsx@@ -5,10 +5,8 @@ import { BrandButton } from "#/components/features/settings/brand-button";import { SettingsInput } from "#/components/features/settings/settings-input";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { CreateApiKeyResponse } from "#/api/api-keys";-import {- displayErrorToast,- displaySuccessToast,-} from "#/utils/custom-toast-handlers";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { mutateWithToast } from "#/utils/mutate-with-toast";import { ApiKeyModalBase } from "./api-key-modal-base";import { useCreateApiKey } from "#/hooks/mutation/use-create-api-key";@@ -34,13 +32,14 @@ export function CreateApiKeyModal({return;}- try {- const newKey = await createApiKeyMutation.mutateAsync(newKeyName);+ const newKey = await mutateWithToast(createApiKeyMutation, newKeyName, {+ success: t(I18nKey.SETTINGS$API_KEY_CREATED),+ error: t(I18nKey.ERROR$GENERIC),+ }).catch(() => null);++ if (newKey) {onKeyCreated(newKey);- displaySuccessToast(t(I18nKey.SETTINGS$API_KEY_CREATED));setNewKeyName("");- } catch {- displayErrorToast(t(I18nKey.ERROR$GENERIC));}};diff --git a/frontend/src/components/features/settings/delete-api-key-modal.tsx b/frontend/src/components/features/settings/delete-api-key-modal.tsxindex 2bcb282227..ee716f9e7c 100644--- a/frontend/src/components/features/settings/delete-api-key-modal.tsx+++ b/frontend/src/components/features/settings/delete-api-key-modal.tsx@@ -4,10 +4,7 @@ import { I18nKey } from "#/i18n/declaration";import { BrandButton } from "#/components/features/settings/brand-button";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { ApiKey } from "#/api/api-keys";-import {- displayErrorToast,- displaySuccessToast,-} from "#/utils/custom-toast-handlers";+import { mutateWithToast } from "#/utils/mutate-with-toast";import { ApiKeyModalBase } from "./api-key-modal-base";import { useDeleteApiKey } from "#/hooks/mutation/use-delete-api-key";@@ -28,12 +25,13 @@ export function DeleteApiKeyModal({const handleDeleteKey = async () => {if (!keyToDelete) return;- try {- await deleteApiKeyMutation.mutateAsync(keyToDelete.id);- displaySuccessToast(t(I18nKey.SETTINGS$API_KEY_DELETED));+ const result = await mutateWithToast(deleteApiKeyMutation, keyToDelete.id, {+ success: t(I18nKey.SETTINGS$API_KEY_DELETED),+ error: t(I18nKey.ERROR$GENERIC),+ }).catch(() => null);++ if (result !== null) {onClose();- } catch {- displayErrorToast(t(I18nKey.ERROR$GENERIC));}};diff --git a/frontend/src/mocks/api-keys-handlers.ts b/frontend/src/mocks/api-keys-handlers.tsnew file mode 100644index 0000000000..339eee26de--- /dev/null+++ b/frontend/src/mocks/api-keys-handlers.ts@@ -0,0 +1,86 @@+import { http, HttpResponse } from "msw";+import { ApiKey, CreateApiKeyResponse } from "#/api/api-keys";++let nextId = 2;++const DEFAULT_API_KEYS: ApiKey[] = [+ {+ id: "1",+ name: "My Dev Key",+ prefix: "oh_dev_",+ created_at: "2025-12-01T10:00:00Z",+ last_used_at: "2026-02-18T14:30:00Z",+ },+ {+ id: "2",+ name: "CI/CD Pipeline",+ prefix: "oh_ci_",+ created_at: "2026-01-15T08:00:00Z",+ last_used_at: null,+ },+];++const apiKeys = new Map<string, ApiKey>(+ DEFAULT_API_KEYS.map((key) => [key.id, key]),+);++export const API_KEYS_HANDLERS = [+ // GET /api/keys - List all API keys+ http.get("/api/keys", () => HttpResponse.json(Array.from(apiKeys.values()))),++ // POST /api/keys - Create a new API key+ http.post("/api/keys", async ({ request }) => {+ const body = (await request.json()) as { name: string };++ if (!body?.name?.trim()) {+ return HttpResponse.json({ error: "Name is required" }, { status: 400 });+ }++ nextId += 1;+ const id = String(nextId);+ const newKey: ApiKey = {+ id,+ name: body.name,+ prefix: `oh_${id}_`,+ created_at: new Date().toISOString(),+ last_used_at: null,+ };+ apiKeys.set(id, newKey);++ const response: CreateApiKeyResponse = {+ id: newKey.id,+ name: newKey.name,+ key: `oh_${id}_sk_mock_${Math.random().toString(36).slice(2, 14)}`,+ prefix: newKey.prefix,+ created_at: newKey.created_at,+ };++ return HttpResponse.json(response);+ }),++ // DELETE /api/keys/:id - Delete an API key+ http.delete("/api/keys/:id", ({ params }) => {+ const { id } = params;++ if (typeof id === "string" && apiKeys.has(id)) {+ apiKeys.delete(id);+ return HttpResponse.json({ success: true });+ }++ return HttpResponse.json({ error: "Key not found" }, { status: 404 });+ }),++ // GET /api/keys/llm/byor - Get LLM API key+ http.get("/api/keys/llm/byor", () =>+ HttpResponse.json({+ key: "sk-mock-llm-api-key-1234567890abcdef",+ }),+ ),++ // POST /api/keys/llm/byor/refresh - Refresh LLM API key+ http.post("/api/keys/llm/byor/refresh", () =>+ HttpResponse.json({+ key: `sk-mock-llm-refreshed-${Math.random().toString(36).slice(2, 14)}`,+ }),+ ),+];diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex 999903ba93..afaf4c1587 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -1,3 +1,4 @@+import { API_KEYS_HANDLERS } from "./api-keys-handlers";import { STRIPE_BILLING_HANDLERS } from "./billing-handlers";import { FILE_SERVICE_HANDLERS } from "./file-service-handlers";import { TASK_SUGGESTIONS_HANDLERS } from "./task-suggestions-handlers";@@ -14,6 +15,7 @@ import { FEEDBACK_HANDLERS } from "./feedback-handlers";import { ANALYTICS_HANDLERS } from "./analytics-handlers";export const handlers = [+ ...API_KEYS_HANDLERS,...STRIPE_BILLING_HANDLERS,...FILE_SERVICE_HANDLERS,...TASK_SUGGESTIONS_HANDLERS,diff --git a/frontend/src/utils/mutate-with-toast.ts b/frontend/src/utils/mutate-with-toast.tsnew file mode 100644index 0000000000..c0fba2a1c0--- /dev/null+++ b/frontend/src/utils/mutate-with-toast.ts@@ -0,0 +1,58 @@+import toast from "react-hot-toast";+import i18next from "i18next";+import { UseMutationResult } from "@tanstack/react-query";+import {+ TOAST_OPTIONS,+ displaySuccessToast,+ displayErrorToast,+} from "./custom-toast-handlers";++export type ToastMessages<TData> = {+ success?: string | ((data: TData) => string) | false;+ error?: string | ((error: Error) => string) | false;+ loading?: string;+};++export async function mutateWithToast<TData, TVariables>(+ mutation: UseMutationResult<TData, Error, TVariables>,+ variables: TVariables,+ messages: ToastMessages<TData>,+): Promise<TData> {+ const { success, error, loading } = messages;++ let loadingToastId: string | undefined;+ if (loading) {+ loadingToastId = toast.loading(loading, TOAST_OPTIONS);+ }++ try {+ const result = await mutation.mutateAsync(variables);++ if (loadingToastId) toast.dismiss(loadingToastId);++ if (success !== false) {+ const message = typeof success === "function" ? success(result) : success;+ if (message) displaySuccessToast(message);+ }++ return result;+ } catch (err) {+ if (loadingToastId) toast.dismiss(loadingToastId);++ if (error !== false) {+ let message: string;+ if (typeof error === "function") {+ message = error(err as Error);+ } else if (error) {+ message = error;+ } else if (err instanceof Error) {+ message = err.message;+ } else {+ message = i18next.t("ERROR$GENERIC");+ }+ displayErrorToast(message);+ }++ throw err;+ }+}