Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Run server actions through TanStack Query and refresh from the server (#3367)

Luke Vella623ea03d1e95
diff --git a/apps/web/package.json b/apps/web/package.json
index 7810caab7..5b33393c7 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -30,6 +30,7 @@
"@hono/zod-validator": "^0.7.2",
"@hookform/resolvers": "^5.2.2",
"@marsidev/react-turnstile": "^1.5.3",
+ "@next-safe-action/adapter-tanstack-query": "0.1.2",
"@next/env": "16.3.3",
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/cancel-invite-button.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/cancel-invite-button.tsx
index d99d9a3d0..f075aee89 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/cancel-invite-button.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/cancel-invite-button.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -12,9 +13,9 @@ import {
useDialog,
} from "@rallly/ui/dialog";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { cancelInviteAction } from "@/features/space/member/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function CancelInviteButton({
inviteId,
@@ -27,18 +28,20 @@ export function CancelInviteButton({
}) {
const cancelInviteDialog = useDialog();
const { t } = useTranslation();
- const cancelInvite = useSafeAction(cancelInviteAction, {
- onSuccess: () => {
- toast.success(
- t("inviteCanceledSuccess", {
- defaultValue: "Invite canceled successfully",
- }),
- );
- },
- onSettled: () => {
- cancelInviteDialog.dismiss();
- },
- });
+ const cancelInvite = useMutation(
+ mutationOptions(cancelInviteAction, {
+ onSuccess: () => {
+ toast.success(
+ t("inviteCanceledSuccess", {
+ defaultValue: "Invite canceled successfully",
+ }),
+ );
+ },
+ onSettled: () => {
+ cancelInviteDialog.dismiss();
+ },
+ }),
+ );
return (
<>
@@ -68,9 +71,9 @@ export function CancelInviteButton({
<DialogFooter>
<Button
variant="destructive"
- loading={cancelInvite.isExecuting}
+ loading={cancelInvite.isPending}
onClick={() => {
- cancelInvite.execute({ inviteId });
+ cancelInvite.mutate({ inviteId });
}}
>
<Trans i18nKey="confirm" defaults="Confirm" />
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/invite-member-dialog.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/invite-member-dialog.tsx
index 86ea83982..c9940b666 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/invite-member-dialog.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/invite-member-dialog.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
@@ -28,6 +29,7 @@ import {
SelectValue,
} from "@rallly/ui/select";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { CheckIcon, XIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
@@ -37,7 +39,6 @@ import { inviteMemberAction } from "@/features/space/member/actions";
import type { MemberRole } from "@/features/space/schema";
import { memberRoleSchema } from "@/features/space/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
function useInviteMemberFormSchema() {
const { t } = useTranslation();
@@ -132,75 +133,73 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {
resolver: zodResolver(formSchema),
});
- const inviteMember = useSafeAction(inviteMemberAction, {
- onSuccess: ({ data }) => {
- if (!data) {
- return;
- }
-
- if (data.ok) {
- switch (data.code) {
- case "INVITE_SENT":
- toast.success(
- t("inviteSent", {
- defaultValue: "Invitation sent",
- }),
- );
- form.reset();
- break;
- case "INVITE_UPDATED":
- toast.success(
- t("inviteUpdated", {
- defaultValue: "Invitation updated with new role",
- }),
- );
- form.reset();
- break;
- }
- onSuccess?.();
- } else {
- switch (data.reason) {
- case "ALREADY_MEMBER":
- form.setError("email", {
- type: "manual",
- message: t("alreadyMember", {
- defaultValue: "This person is already a member of this space",
- }),
- });
- break;
- case "INVITE_PENDING":
- form.setError("email", {
- type: "manual",
- message: t("invitePending", {
- defaultValue:
- "An invitation has already been sent to this email address",
- }),
- });
- break;
- case "NOT_ENOUGH_SEATS":
- form.setError("root", {
- type: "manual",
- message: t("inviteNotEnoughSeats", {
- defaultValue:
- "There are not enough seats available to send this invite",
- }),
- });
- break;
- case "INVITE_FAILED":
- form.setError("root", {
- type: "manual",
- message: t("inviteFailed", {
- defaultValue: "Failed to send invitation",
- }),
- });
- break;
+ const inviteMember = useMutation(
+ mutationOptions(inviteMemberAction, {
+ onSuccess: (data) => {
+ if (data.ok) {
+ switch (data.code) {
+ case "INVITE_SENT":
+ toast.success(
+ t("inviteSent", {
+ defaultValue: "Invitation sent",
+ }),
+ );
+ form.reset();
+ break;
+ case "INVITE_UPDATED":
+ toast.success(
+ t("inviteUpdated", {
+ defaultValue: "Invitation updated with new role",
+ }),
+ );
+ form.reset();
+ break;
+ }
+ onSuccess?.();
+ } else {
+ switch (data.reason) {
+ case "ALREADY_MEMBER":
+ form.setError("email", {
+ type: "manual",
+ message: t("alreadyMember", {
+ defaultValue: "This person is already a member of this space",
+ }),
+ });
+ break;
+ case "INVITE_PENDING":
+ form.setError("email", {
+ type: "manual",
+ message: t("invitePending", {
+ defaultValue:
+ "An invitation has already been sent to this email address",
+ }),
+ });
+ break;
+ case "NOT_ENOUGH_SEATS":
+ form.setError("root", {
+ type: "manual",
+ message: t("inviteNotEnoughSeats", {
+ defaultValue:
+ "There are not enough seats available to send this invite",
+ }),
+ });
+ break;
+ case "INVITE_FAILED":
+ form.setError("root", {
+ type: "manual",
+ message: t("inviteFailed", {
+ defaultValue: "Failed to send invitation",
+ }),
+ });
+ break;
+ }
}
- }
- },
- });
+ },
+ }),
+ );
return (
<Form {...form}>
- <form onSubmit={form.handleSubmit((data) => inviteMember.execute(data))}>
+ <form onSubmit={form.handleSubmit((data) => inviteMember.mutate(data))}>
<div className="space-y-4">
<FormField
control={form.control}
@@ -266,7 +265,7 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {
<div className="mt-4 flex">
<Button
variant="primary"
- loading={inviteMember.isExecuting}
+ loading={inviteMember.isPending}
type="submit"
>
<Trans i18nKey="inviteMemberFormSubmit" defaults="Send invite" />
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/member-dropdown-menu.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/member-dropdown-menu.tsx
index 787b4811b..e95e3c68d 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/member-dropdown-menu.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/members/components/member-dropdown-menu.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -19,6 +20,7 @@ import {
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { MoreHorizontalIcon, ShieldIcon, UserIcon, XIcon } from "lucide-react";
import {
changeMemberRoleAction,
@@ -27,7 +29,6 @@ import {
import type { MemberDTO } from "@/features/space/member/types";
import type { MemberRole } from "@/features/space/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function MemberDropdownMenu({
member,
@@ -40,30 +41,34 @@ export function MemberDropdownMenu({
}) {
const removeMemberDialog = useDialog();
const { t } = useTranslation();
- const removeMember = useSafeAction(removeMemberAction, {
- onSuccess: () => {
- toast.success(
- t("removeMemberSuccess", {
- defaultValue: "Member removed successfully",
- }),
- );
- },
- onSettled: () => {
- removeMemberDialog.dismiss();
- },
- });
- const changeMemberRole = useSafeAction(changeMemberRoleAction, {
- onSuccess: () => {
- toast.success(
- t("roleChangedSuccess", {
- defaultValue: "Role changed successfully",
- }),
- );
- },
- });
+ const removeMember = useMutation(
+ mutationOptions(removeMemberAction, {
+ onSuccess: () => {
+ toast.success(
+ t("removeMemberSuccess", {
+ defaultValue: "Member removed successfully",
+ }),
+ );
+ },
+ onSettled: () => {
+ removeMemberDialog.dismiss();
+ },
+ }),
+ );
+ const changeMemberRole = useMutation(
+ mutationOptions(changeMemberRoleAction, {
+ onSuccess: () => {
+ toast.success(
+ t("roleChangedSuccess", {
+ defaultValue: "Role changed successfully",
+ }),
+ );
+ },
+ }),
+ );
const handleRoleChange = (newRole: MemberRole) => {
- changeMemberRole.execute({
+ changeMemberRole.mutate({
memberId: member.id,
role: newRole,
});
@@ -131,9 +136,9 @@ export function MemberDropdownMenu({
<DialogFooter>
<Button
variant="destructive"
- loading={removeMember.isExecuting}
+ loading={removeMember.isPending}
onClick={() => {
- removeMember.execute({ memberId: member.id });
+ removeMember.mutate({ memberId: member.id });
}}
>
<Trans i18nKey="confirm" defaults="Confirm" />
diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx
index d2f6a4e5e..8fc05543b 100644
--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Alert, AlertDescription } from "@rallly/ui/alert";
import { Button } from "@rallly/ui/button";
import {
@@ -20,9 +21,9 @@ import {
FormLabel,
FormMessage,
} from "@rallly/ui/form";
-
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { AlertTriangleIcon, CheckIcon, CopyIcon, PlusIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
@@ -30,13 +31,15 @@ import { useCopyToClipboard } from "react-use";
import { createApiKeyAction } from "@/features/api-keys/actions";
import { createApiKeySchema } from "@/features/api-keys/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function CreateApiKeyButton() {
const { t } = useTranslation();
const dialog = useDialog();
const [createdApiKey, setCreatedApiKey] = React.useState<string | null>(null);
- const createApiKey = useSafeAction(createApiKeyAction);
+ // The result carries the plaintext key; keep it out of the mutation cache
+ const createApiKey = useMutation(
+ mutationOptions(createApiKeyAction, { gcTime: 0 }),
+ );
const [, copy] = useCopyToClipboard();
const [didCopy, setDidCopy] = React.useState(false);
@@ -49,6 +52,7 @@ export function CreateApiKeyButton() {
const handleClose = () => {
dialog.dismiss();
+ createApiKey.reset();
setCreatedApiKey(null);
form.reset();
};
@@ -145,20 +149,20 @@ export function CreateApiKeyButton() {
<Form {...form}>
<form
onSubmit={form.handleSubmit(async (data) => {
- const result = await createApiKey.executeAsync(data);
- if (result?.data?.ok) {
- setCreatedApiKey(result.data.apiKey);
- form.reset();
- } else if (
- result?.data?.reason === "max_api_keys_exceeded"
- ) {
- toast.error(
- t("apiKeyLimitReached", {
- defaultValue:
- "You've reached the maximum number of API keys. Revoke one before creating another.",
- }),
- );
- }
+ try {
+ const result = await createApiKey.mutateAsync(data);
+ if (result.ok) {
+ setCreatedApiKey(result.apiKey);
+ form.reset();
+ } else if (result.reason === "max_api_keys_exceeded") {
+ toast.error(
+ t("apiKeyLimitReached", {
+ defaultValue:
+ "You've reached the maximum number of API keys. Revoke one before creating another.",
+ }),
+ );
+ }
+ } catch {}
})}
>
<div className="space-y-4">
@@ -188,8 +192,8 @@ export function CreateApiKeyButton() {
<Button
variant="primary"
type="submit"
- disabled={createApiKey.isExecuting}
- loading={createApiKey.isExecuting}
+ disabled={createApiKey.isPending}
+ loading={createApiKey.isPending}
>
<Trans i18nKey="create" defaults="Create" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx
index d5bdbe2dd..58a2d0d65 100644
--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -18,10 +19,10 @@ import {
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { BanIcon, MoreVerticalIcon } from "lucide-react";
import { revokeApiKeyAction } from "@/features/api-keys/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function RevokeApiKeyButton({
apiKeyId,
@@ -32,14 +33,16 @@ export function RevokeApiKeyButton({
}) {
const { t } = useTranslation();
const revokeDialog = useDialog();
- const revokeApiKey = useSafeAction(revokeApiKeyAction, {
- onSuccess: () => {
- toast.success(t("revoked", { defaultValue: "Revoked" }));
- },
- onSettled: () => {
- revokeDialog.dismiss();
- },
- });
+ const revokeApiKey = useMutation(
+ mutationOptions(revokeApiKeyAction, {
+ onSuccess: () => {
+ toast.success(t("revoked", { defaultValue: "Revoked" }));
+ },
+ onSettled: () => {
+ revokeDialog.dismiss();
+ },
+ }),
+ );
return (
<>
@@ -87,9 +90,9 @@ export function RevokeApiKeyButton({
<DialogFooter>
<Button
variant="destructive"
- loading={revokeApiKey.isExecuting}
+ loading={revokeApiKey.isPending}
onClick={() => {
- revokeApiKey.execute({ id: apiKeyId });
+ revokeApiKey.mutate({ id: apiKeyId });
}}
>
<Trans i18nKey="revoke" defaults="Revoke" />
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-and-billing-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-and-billing-card.tsx
index aaa0645b8..89b097aad 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-and-billing-card.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-and-billing-card.tsx
@@ -1,11 +1,12 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
+import { useMutation } from "@tanstack/react-query";
import { ArrowUpRightIcon, CreditCardIcon } from "lucide-react";
import { openBillingDetailsAction } from "@/features/billing/actions";
import type { PaymentMethodCard } from "@/features/billing/schema";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import {
PlanCard,
PlanCardActions,
@@ -41,7 +42,9 @@ export function PaymentAndBillingCard({
}[];
className?: string;
}) {
- const openBillingDetails = useSafeAction(openBillingDetailsAction);
+ const openBillingDetails = useMutation(
+ mutationOptions(openBillingDetailsAction),
+ );
const [primary] = paymentMethods;
return (
@@ -102,8 +105,8 @@ export function PaymentAndBillingCard({
</PlanCardContent>
<PlanCardActions>
<Button
- loading={openBillingDetails.isExecuting}
- onClick={() => openBillingDetails.execute()}
+ loading={openBillingDetails.isPending}
+ onClick={() => openBillingDetails.mutate()}
>
<Trans i18nKey="manageBilling" defaults="Manage billing" />
<ArrowUpRightIcon className="text-muted-foreground" />
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
index c05450901..9abe6bc19 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
@@ -18,8 +18,9 @@ vi.mock("@/features/billing/actions", () => ({
resumePlanAction: vi.fn(),
}));
-vi.mock("@/lib/safe-action/client", () => ({
- useSafeAction: () => ({ execute: vi.fn(), isExecuting: false }),
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),
}));
vi.mock("@/lib/datetime/client", () => ({
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
index 2e17af7d1..8c4c4082a 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
@@ -1,9 +1,11 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { posthog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import { DialogTrigger, useDialog } from "@rallly/ui/dialog";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { TriangleAlertIcon } from "lucide-react";
import {
openCancelPlanAction,
@@ -20,7 +22,6 @@ import { formatMinorUnitAmount } from "@/features/billing/utils";
import { SpaceTierLabel } from "@/features/space/components/space-tier";
import { Trans, useTranslation } from "@/i18n/client";
import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { ManageSeatsDialog } from "./manage-seats-dialog";
import {
PlanCard,
@@ -73,15 +74,19 @@ export function ProPlanCard({
const { locale } = useDateTimeConfig();
const { formatDateTime } = useDateTime();
const switchToYearlyDialog = useDialog();
- const openCancelPlan = useSafeAction(openCancelPlanAction);
- const openPaymentMethodUpdate = useSafeAction(openPaymentMethodUpdateAction);
- const resumePlan = useSafeAction(resumePlanAction, {
- onSuccess: () => {
- toast.success(
- t("planResumedToast", { defaultValue: "Your plan will renew" }),
- );
- },
- });
+ const openCancelPlan = useMutation(mutationOptions(openCancelPlanAction));
+ const openPaymentMethodUpdate = useMutation(
+ mutationOptions(openPaymentMethodUpdateAction),
+ );
+ const resumePlan = useMutation(
+ mutationOptions(resumePlanAction, {
+ onSuccess: () => {
+ toast.success(
+ t("planResumedToast", { defaultValue: "Your plan will renew" }),
+ );
+ },
+ }),
+ );
const formatCurrency = (minorUnitAmount: number) =>
formatMinorUnitAmount({ amount: minorUnitAmount, currency, locale });
@@ -178,8 +183,8 @@ export function ProPlanCard({
{endsAtPeriodEnd ? (
canResume ? (
<Button
- loading={resumePlan.isExecuting}
- onClick={() => resumePlan.execute()}
+ loading={resumePlan.isPending}
+ onClick={() => resumePlan.mutate()}
>
<Trans i18nKey="resumePlan" defaults="Resume plan" />
</Button>
@@ -188,8 +193,8 @@ export function ProPlanCard({
<>
{needsPayment ? (
<Button
- loading={openPaymentMethodUpdate.isExecuting}
- onClick={() => openPaymentMethodUpdate.execute()}
+ loading={openPaymentMethodUpdate.isPending}
+ onClick={() => openPaymentMethodUpdate.mutate()}
>
<TriangleAlertIcon className="text-amber-500" />
<Trans
@@ -265,8 +270,8 @@ export function ProPlanCard({
<Button
variant="ghost"
className="text-muted-foreground"
- loading={openCancelPlan.isExecuting}
- onClick={() => openCancelPlan.execute()}
+ loading={openCancelPlan.isPending}
+ onClick={() => openCancelPlan.mutate()}
>
<Trans i18nKey="cancelPlan" defaults="Cancel plan" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx
index a6ef66f8a..9d3c72aea 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { yearlySavingsPercent } from "@rallly/billing";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
@@ -12,9 +13,9 @@ import {
DialogHeader,
DialogTitle,
} from "@rallly/ui/dialog";
+import { useMutation } from "@tanstack/react-query";
import { switchToYearlyAction } from "@/features/billing/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function SwitchToYearlyDialog({
children,
@@ -27,7 +28,7 @@ export function SwitchToYearlyDialog({
/** Per seat yearly amount in the currency's minor unit. */
yearlyAmount: number;
}) {
- const switchToYearly = useSafeAction(switchToYearlyAction);
+ const switchToYearly = useMutation(mutationOptions(switchToYearlyAction));
return (
<Dialog {...dialogProps}>
@@ -59,8 +60,8 @@ export function SwitchToYearlyDialog({
</DialogClose>
<Button
variant="primary"
- loading={switchToYearly.isExecuting}
- onClick={() => switchToYearly.execute()}
+ loading={switchToYearly.isPending}
+ onClick={() => switchToYearly.mutate()}
>
<Trans i18nKey="switchToYearly" defaults="Switch to yearly" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/collaboration-section.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/collaboration-section.tsx
index bb19926a5..2c5b55bd3 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/collaboration-section.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/collaboration-section.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { cn } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import {
@@ -11,6 +12,7 @@ import {
} from "@rallly/ui/field";
import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
+import { useMutation } from "@tanstack/react-query";
import { UsersIcon } from "lucide-react";
import React from "react";
import {
@@ -26,7 +28,6 @@ import { ProBadge } from "@/features/billing/components/pro-badge";
import { updateSpaceSharedAction } from "@/features/space/actions";
import { useSpace } from "@/features/space/client";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function CollaborationSection({
disabled = false,
@@ -37,7 +38,7 @@ export function CollaborationSection({
const { t } = useTranslation();
const isFree = useIsFree();
- const updateShared = useSafeAction(updateSpaceSharedAction);
+ const updateShared = useMutation(mutationOptions(updateSpaceSharedAction));
// Optimistic value shown until the post-action router refresh delivers
// the updated space data; reverts automatically if the action fails.
@@ -74,11 +75,10 @@ export function CollaborationSection({
React.startTransition(async () => {
setOptimisticShared(next);
setPendingShared(null);
- const result = await updateShared.executeAsync({ shared: next });
-
- if (!result?.serverError && !result?.validationErrors) {
+ try {
+ await updateShared.mutateAsync({ shared: next });
toast.success(t("saved", { defaultValue: "Saved" }));
- }
+ } catch {}
});
};
@@ -123,7 +123,7 @@ export function CollaborationSection({
size="sm"
variant="primary"
onClick={handleSave}
- loading={updateShared.isExecuting}
+ loading={updateShared.isPending}
className={cn(!showSaveButton && "invisible")}
>
<Trans i18nKey="save" defaults="Save" />
@@ -132,7 +132,7 @@ export function CollaborationSection({
id="space-shared"
checked={checked}
onCheckedChange={handleToggle}
- disabled={disabled || updateShared.isExecuting}
+ disabled={disabled || updateShared.isPending}
/>
</div>
</Field>
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
index fdb692c8c..ec88b5e54 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Alert, AlertDescription } from "@rallly/ui/alert";
import { parseColor } from "@rallly/ui/color-picker";
import {
@@ -12,6 +13,7 @@ import {
} from "@rallly/ui/field";
import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
+import { useMutation } from "@tanstack/react-query";
import { LockIcon } from "lucide-react";
import React from "react";
import { ColorPickerWithSaveButton } from "@/components/color-picker-with-save-button";
@@ -33,7 +35,6 @@ import {
import { useSpace } from "@/features/space/client";
import { useAuthedUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { BrandingPreview } from "./branding-preview";
import { RemoveAttributionSetting } from "./remove-attribution-setting";
@@ -55,8 +56,10 @@ export function CustomBrandingSection({
const isDefault =
hexColor.toLowerCase() === DEFAULT_PRIMARY_COLOR.toLowerCase();
- const updateShowBranding = useSafeAction(updateSpaceShowBrandingAction);
- const updateSpace = useSafeAction(updateSpaceAction);
+ const updateShowBranding = useMutation(
+ mutationOptions(updateSpaceShowBrandingAction),
+ );
+ const updateSpace = useMutation(mutationOptions(updateSpaceAction));
// Optimistic value shown until the post-action router refresh delivers
// the updated space data; reverts automatically if the action fails.
@@ -72,22 +75,18 @@ export function CustomBrandingSection({
React.startTransition(async () => {
setOptimisticShowBranding(newChecked);
- const result = await updateShowBranding.executeAsync({
- showBranding: newChecked,
- });
-
- if (!result?.serverError && !result?.validationErrors) {
+ try {
+ await updateShowBranding.mutateAsync({ showBranding: newChecked });
toast.success(t("saved", { defaultValue: "Saved" }));
- }
+ } catch {}
});
};
const persistColor = async (value: string | null) => {
- const result = await updateSpace.executeAsync({ primaryColor: value });
-
- if (!result?.serverError && !result?.validationErrors) {
+ try {
+ await updateSpace.mutateAsync({ primaryColor: value });
toast.success(t("saved", { defaultValue: "Saved" }));
- }
+ } catch {}
};
const handleSave = () => {
@@ -156,7 +155,7 @@ export function CustomBrandingSection({
value={color}
onChange={setColor}
disabled={disabled}
- isSaving={updateSpace.isExecuting}
+ isSaving={updateSpace.isPending}
onSave={handleSave}
onReset={handleReset}
showReset={!isDefault}
@@ -187,7 +186,7 @@ export function CustomBrandingSection({
id="show-branding"
checked={showBranding}
onCheckedChange={handleToggle}
- disabled={disabled || updateShowBranding.isExecuting}
+ disabled={disabled || updateShowBranding.isPending}
/>
</Field>
<BrandingPreview
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/delete-space-button.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/delete-space-button.tsx
index 3fe7291d8..0daea0f1a 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/delete-space-button.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/delete-space-button.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
@@ -24,12 +25,12 @@ import {
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { deleteSpaceAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
interface DeleteSpaceDialogProps extends DialogProps {
spaceName: string;
@@ -49,16 +50,18 @@ function DeleteSpaceDialog({
const router = useRouter();
const { t } = useTranslation();
- const deleteSpace = useSafeAction(deleteSpaceAction, {
- onSuccess: () => {
- toast.success(
- t("deletedSpaceSuccess", {
- defaultValue: "Space has been permanently deleted",
- }),
- );
- router.push("/");
- },
- });
+ const deleteSpace = useMutation(
+ mutationOptions(deleteSpaceAction, {
+ onSuccess: () => {
+ toast.success(
+ t("deletedSpaceSuccess", {
+ defaultValue: "Space has been permanently deleted",
+ }),
+ );
+ router.push("/");
+ },
+ }),
+ );
return (
<Form {...form}>
@@ -67,7 +70,7 @@ function DeleteSpaceDialog({
<DialogContent>
<form
onSubmit={form.handleSubmit(() => {
- deleteSpace.execute();
+ deleteSpace.mutate();
})}
>
<DialogHeader>
@@ -132,7 +135,7 @@ function DeleteSpaceDialog({
</DialogClose>
<Button
type="submit"
- loading={deleteSpace.isExecuting}
+ loading={deleteSpace.isPending}
variant="destructive"
>
<Trans
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/remove-attribution-setting.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/remove-attribution-setting.tsx
index ce38215a3..9456ba2fd 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/remove-attribution-setting.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/remove-attribution-setting.tsx
@@ -17,7 +17,7 @@ export function RemoveAttributionSetting({
disabled?: boolean;
}) {
const { data: space } = useSpace();
- const { hideAttribution, isExecuting, toggle } = useHideAttributionToggle({
+ const { hideAttribution, isPending, toggle } = useHideAttributionToggle({
hideAttribution: space.hideAttribution,
payWallTrigger: { from: "custom-branding", setting: "hide_attribution" },
});
@@ -43,7 +43,7 @@ export function RemoveAttributionSetting({
id="hide-attribution"
checked={hideAttribution}
onCheckedChange={toggle}
- disabled={disabled || isExecuting}
+ disabled={disabled || isPending}
/>
</Field>
);
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
index aa90d592e..6cb1f6940 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import {
Field,
FieldContent,
@@ -10,6 +11,7 @@ import {
FieldTitle,
} from "@rallly/ui/field";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import type React from "react";
import type { Control } from "react-hook-form";
import { Controller, useForm } from "react-hook-form";
@@ -30,7 +32,6 @@ import { SpaceIcon } from "@/features/space/components/space-icon";
import { spaceIconAssetProfile } from "@/features/space/constants";
import type { SpaceDTO } from "@/features/space/types";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
const spaceSettingsSchema = z.object({
name: z
@@ -52,10 +53,12 @@ export function SpaceSettingsForm({
}: SpaceSettingsFormProps) {
const { t } = useTranslation();
- const updateSpace = useSafeAction(updateSpaceAction);
- const getImageUploadUrl = useSafeAction(getSpaceImageUploadUrlAction);
- const updateImage = useSafeAction(updateSpaceImageAction);
- const removeImage = useSafeAction(removeSpaceImageAction);
+ const updateSpace = useMutation(mutationOptions(updateSpaceAction));
+ const getImageUploadUrl = useMutation(
+ mutationOptions(getSpaceImageUploadUrlAction),
+ );
+ const updateImage = useMutation(mutationOptions(updateSpaceImageAction));
+ const removeImage = useMutation(mutationOptions(removeSpaceImageAction));
const form = useForm({
resolver: zodResolver(spaceSettingsSchema),
@@ -85,9 +88,14 @@ export function SpaceSettingsForm({
<ImageUploadControl
profile={spaceIconAssetProfile}
crop
- signUpload={(input) => getImageUploadUrl.executeAsync(input)}
- persistUpload={(imageKey) => updateImage.executeAsync({ imageKey })}
- onRemove={() => removeImage.executeAsync()}
+ signUpload={(input) => getImageUploadUrl.mutateAsync(input)}
+ persistUpload={(imageKey) => updateImage.mutateAsync({ imageKey })}
+ onRemove={async () => {
+ // A rejection inside ImageUpload's transition would reach the error boundary
+ try {
+ await removeImage.mutateAsync();
+ } catch {}
+ }}
hasCurrentImage={!!space.image}
/>
</ImageUpload>
@@ -107,21 +115,18 @@ export function SpaceSettingsForm({
<SpaceNameField
control={form.control}
disabled={disabled}
- isSaving={updateSpace.isExecuting}
+ isSaving={updateSpace.isPending}
isDirty={form.formState.isDirty}
onSubmit={form.handleSubmit(async (data) => {
- const result = await updateSpace.executeAsync({
- name: data.name,
- });
-
- if (!result?.serverError && !result?.validationErrors) {
+ try {
+ await updateSpace.mutateAsync({ name: data.name });
form.reset(data);
toast.success(
t("spaceUpdatedSuccess", {
defaultValue: "Space updated successfully",
}),
);
- }
+ } catch {}
})}
/>
</Field>
diff --git a/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx b/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx
index 969ec7627..9d57c537c 100644
--- a/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import {
Field,
FieldContent,
@@ -9,6 +10,7 @@ import {
} from "@rallly/ui/field";
import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
+import { useMutation } from "@tanstack/react-query";
import { InboxIcon, MessageCircleIcon } from "lucide-react";
import React from "react";
import {
@@ -26,7 +28,6 @@ import type {
NotificationPreferences,
} from "@/features/notifications/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function NotificationsPage({
initialPreferences,
@@ -35,7 +36,9 @@ export function NotificationsPage({
}) {
const { t } = useTranslation();
const [preferences, setPreferences] = React.useState(initialPreferences);
- const updatePreference = useSafeAction(updateNotificationPreferenceAction);
+ const updatePreference = useMutation(
+ mutationOptions(updateNotificationPreferenceAction),
+ );
const setPreference = async (
eventType: ActivityEventType,
@@ -43,13 +46,13 @@ export function NotificationsPage({
) => {
const previous = preferences[eventType];
setPreferences((old) => ({ ...old, [eventType]: enabled }));
- const result = await updatePreference.executeAsync({ eventType, enabled });
- if (result?.serverError || result?.validationErrors) {
+ try {
+ await updatePreference.mutateAsync({ eventType, enabled });
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ } catch {
// Roll back only the toggled field — a full-snapshot restore could
// clobber another toggle that succeeded while this one was in flight.
setPreferences((old) => ({ ...old, [eventType]: previous }));
- } else {
- toast.success(t("saved", { defaultValue: "Saved" }));
}
};
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/components/localization-preferences.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/components/localization-preferences.tsx
index fab50cfa5..dfc8c000d 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/components/localization-preferences.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/components/localization-preferences.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import {
Field,
FieldContent,
@@ -15,6 +16,7 @@ import {
SelectValue,
} from "@rallly/ui/select";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import {
CalendarIcon,
ClockIcon,
@@ -31,7 +33,6 @@ import { useDateTime } from "@/lib/datetime/client";
import { getLocaleDefaults } from "@/lib/datetime/locales";
import type { TimeFormat } from "@/lib/datetime/types";
import { setLocaleCookie, useLocale } from "@/lib/locale/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
export const LocalizationPreferences = ({
@@ -48,7 +49,9 @@ export const LocalizationPreferences = ({
const { locale } = useLocale();
const localeDefaults = getLocaleDefaults(locale);
const { weekdays } = useDateTime();
- const updateLocalization = useSafeAction(updateLocalizationAction);
+ const updateLocalization = useMutation(
+ mutationOptions(updateLocalizationAction),
+ );
const [language, setLanguage] = React.useState(
initialValues.locale ?? locale,
@@ -69,12 +72,13 @@ export const LocalizationPreferences = ({
timeFormat?: TimeFormat;
weekStart?: number;
}) => {
- const result = await updateLocalization.executeAsync(input);
- const saved = !result?.serverError && !result?.validationErrors;
- if (saved) {
- toast.success(t("saved", { defaultValue: "Saved" }));
+ try {
+ await updateLocalization.mutateAsync(input);
+ } catch {
+ return false;
}
- return saved;
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ return true;
};
const weekStartOptions = weekdays().map(({ day, label }) => ({
@@ -115,8 +119,8 @@ export const LocalizationPreferences = ({
}
const previousLanguage = language;
setLanguage(nextLanguage);
- // Set the cookie before executing: useSafeAction refreshes the
- // router on success, and that refresh must read the new locale.
+ // Set the cookie before executing: the action refreshes the
+ // page on success, and that refresh must read the new locale.
// Writing the cookie server-side would collide with
// updateUser's session cookie and drop it. Roll it back to the
// locale this page is rendered in if the save doesn't land.
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
index b0f636f80..c5bef4d75 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
@@ -1,6 +1,8 @@
"use server";
+
import { subject } from "@casl/ability";
import { sendAccountDeletionScheduledEmail } from "@rallly/emails/templates/account-deletion-scheduled";
+import { refresh } from "next/cache";
import { after } from "next/server";
import { getInstanceBranding } from "@/emails/branding";
import {
@@ -84,6 +86,8 @@ export const scheduleAccountDeletionAction = authActionClient
props: { deletionDate },
}),
);
+
+ refresh();
});
// Self-hosted instances have no scheduler running the remove-deleted-users
@@ -123,4 +127,6 @@ export const cancelAccountDeletionAction = authActionClient
await resumeUserSubscriptionRenewals({ userId: ctx.user.id });
track(ctx.user, { event: "account_deletion_cancel" });
+
+ refresh();
});
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx
index adb077ee6..830e1b690 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx
@@ -1,26 +1,29 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { cancelAccountDeletionAction } from "../actions";
export function CancelAccountDeletionButton() {
const { t } = useTranslation();
- const cancelAccountDeletion = useSafeAction(cancelAccountDeletionAction, {
- onSuccess: () => {
- toast.success(
- t("accountDeletionCancelled", {
- defaultValue: "Your account is no longer scheduled for deletion",
- }),
- );
- },
- });
+ const cancelAccountDeletion = useMutation(
+ mutationOptions(cancelAccountDeletionAction, {
+ onSuccess: () => {
+ toast.success(
+ t("accountDeletionCancelled", {
+ defaultValue: "Your account is no longer scheduled for deletion",
+ }),
+ );
+ },
+ }),
+ );
return (
<Button
- loading={cancelAccountDeletion.isExecuting}
- onClick={() => cancelAccountDeletion.executeAsync()}
+ loading={cancelAccountDeletion.isPending}
+ onClick={() => cancelAccountDeletion.mutate()}
>
<Trans i18nKey="cancelAccountDeletion" defaults="Cancel deletion" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx
index d73a3b0cc..ee81f05b7 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/change-email-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -16,6 +17,7 @@ import { Field, FieldError, FieldGroup, FieldLabel } from "@rallly/ui/field";
import { Form } from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import React from "react";
import { Controller, useForm } from "react-hook-form";
@@ -24,7 +26,6 @@ import { InputOTP } from "@/components/input-otp";
import { checkEmailAvailabilityAction } from "@/features/user/actions";
import { Trans, useTranslation } from "@/i18n/client";
import { authClient } from "@/lib/auth-client";
-import { useSafeAction } from "@/lib/safe-action/client";
const emailSchema = z.object({
email: z.email(),
@@ -43,7 +44,9 @@ function RequestEmailChangeForm({
}) {
const { t } = useTranslation();
const emailId = React.useId();
- const checkEmailAvailability = useSafeAction(checkEmailAvailabilityAction);
+ const checkEmailAvailability = useMutation(
+ mutationOptions(checkEmailAvailabilityAction),
+ );
const form = useForm({
defaultValues: { email: currentEmail },
resolver: zodResolver(emailSchema),
@@ -56,16 +59,29 @@ function RequestEmailChangeForm({
onSubmit={form.handleSubmit(async (data) => {
// Better-Auth reports success without sending when the address is
// taken, so the conflict has to be caught before that call.
- const availability = await checkEmailAvailability.executeAsync({
- email: data.email,
- });
+ let availability: Awaited<
+ ReturnType<typeof checkEmailAvailability.mutateAsync>
+ >;
+ try {
+ availability = await checkEmailAvailability.mutateAsync({
+ email: data.email,
+ });
+ } catch {
+ form.setError("email", {
+ message: t("emailChangeRequestError", {
+ defaultValue:
+ "We couldn't process this request. Please try again later.",
+ }),
+ });
+ return;
+ }
- if (availability?.data?.ok === false) {
+ if (!availability.ok) {
form.setError(
"email",
{
message:
- availability.data.reason === "same_email"
+ availability.reason === "same_email"
? t("emailChangeSameAddress", {
defaultValue:
"This is already your email address. Enter a different one.",
@@ -80,16 +96,6 @@ function RequestEmailChangeForm({
return;
}
- if (!availability?.data?.ok) {
- form.setError("email", {
- message: t("emailChangeRequestError", {
- defaultValue:
- "We couldn't process this request. Please try again later.",
- }),
- });
- return;
- }
-
const res = await authClient.emailOtp.requestEmailChange({
newEmail: data.email,
});
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx
index 67c955838..275362625 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx
@@ -1,4 +1,5 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import {
@@ -14,13 +15,13 @@ import {
} from "@rallly/ui/dialog";
import { Form, FormField, FormItem, FormMessage } from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { ACCOUNT_DELETION_GRACE_DAYS } from "@/features/user/account-deletion/constants";
import { useAuthedUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
import { signOut } from "@/lib/auth-client";
import { isSelfHosted } from "@/lib/constants";
-import { useSafeAction } from "@/lib/safe-action/client";
import { deleteAccountAction, scheduleAccountDeletionAction } from "../actions";
export function DeleteAccountDialog(props: {
@@ -43,11 +44,13 @@ function ScheduleAccountDeletionDialog({
summary?: React.ReactNode;
}) {
const dialog = useDialog();
- const scheduleAccountDeletion = useSafeAction(scheduleAccountDeletionAction, {
- onSuccess: () => {
- dialog.dismiss();
- },
- });
+ const scheduleAccountDeletion = useMutation(
+ mutationOptions(scheduleAccountDeletionAction, {
+ onSuccess: () => {
+ dialog.dismiss();
+ },
+ }),
+ );
return (
<Dialog {...dialog.dialogProps}>
@@ -89,8 +92,8 @@ function ScheduleAccountDeletionDialog({
</DialogClose>
<Button
variant="destructive"
- loading={scheduleAccountDeletion.isExecuting}
- onClick={() => scheduleAccountDeletion.executeAsync()}
+ loading={scheduleAccountDeletion.isPending}
+ onClick={() => scheduleAccountDeletion.mutate()}
>
<Trans i18nKey="deleteAccount" defaults="Delete account" />
</Button>
@@ -118,17 +121,19 @@ function InstantDeleteAccountDialog({
},
});
- const deleteAccount = useSafeAction(deleteAccountAction, {
- onSuccess: () => {
- // The server already revoked the session; sign out clears the cookies
- // before leaving the page.
- signOut()
- .catch(() => {})
- .finally(() => {
- window.location.href = "/";
- });
- },
- });
+ const deleteAccount = useMutation(
+ mutationOptions(deleteAccountAction, {
+ onSuccess: () => {
+ // The server already revoked the session; sign out clears the cookies
+ // before leaving the page.
+ signOut()
+ .catch(() => {})
+ .finally(() => {
+ window.location.href = "/";
+ });
+ },
+ }),
+ );
return (
<Form {...form}>
@@ -136,8 +141,8 @@ function InstantDeleteAccountDialog({
<DialogTrigger render={trigger} />
<DialogContent>
<form
- onSubmit={form.handleSubmit(async () => {
- await deleteAccount.executeAsync();
+ onSubmit={form.handleSubmit(() => {
+ deleteAccount.mutate();
})}
>
<DialogHeader>
@@ -207,7 +212,7 @@ function InstantDeleteAccountDialog({
<Button
type="submit"
variant="destructive"
- loading={deleteAccount.isExecuting}
+ loading={deleteAccount.isPending}
>
<Trans i18nKey="deleteAccount" defaults="Delete account" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx
index 9130966f6..ed1bd3037 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx
@@ -1,5 +1,7 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
+import { useMutation } from "@tanstack/react-query";
import {
ImageUpload,
ImageUploadControl,
@@ -13,7 +15,6 @@ import {
} from "@/features/user/actions";
import { avatarAssetProfile } from "@/features/user/constants";
import { useFeatureFlag } from "@/lib/feature-flags/client";
-import { useSafeAction } from "@/lib/safe-action/client";
function ProfilePictureUpload({
image,
@@ -22,9 +23,11 @@ function ProfilePictureUpload({
image?: string;
name: string;
}) {
- const getAvatarUploadUrl = useSafeAction(getAvatarUploadUrlAction);
- const updateUserAvatar = useSafeAction(updateUserAvatarAction);
- const removeUserAvatar = useSafeAction(removeUserAvatarAction);
+ const getAvatarUploadUrl = useMutation(
+ mutationOptions(getAvatarUploadUrlAction),
+ );
+ const updateUserAvatar = useMutation(mutationOptions(updateUserAvatarAction));
+ const removeUserAvatar = useMutation(mutationOptions(removeUserAvatarAction));
return (
<ImageUpload>
@@ -34,11 +37,11 @@ function ProfilePictureUpload({
<ImageUploadControl
profile={avatarAssetProfile}
crop
- signUpload={(input) => getAvatarUploadUrl.executeAsync(input)}
- persistUpload={(imageKey) =>
- updateUserAvatar.executeAsync({ imageKey })
- }
- onRemove={() => removeUserAvatar.executeAsync()}
+ signUpload={(input) => getAvatarUploadUrl.mutateAsync(input)}
+ persistUpload={(imageKey) => updateUserAvatar.mutateAsync({ imageKey })}
+ // The global handler reports the failure; a rejection here would
+ // escape the remove transition.
+ onRemove={() => removeUserAvatar.mutateAsync().catch(() => {})}
hasCurrentImage={!!image}
/>
</ImageUpload>
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsx
index e42fae774..e20a6107f 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsx
@@ -1,5 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Form,
@@ -10,12 +11,12 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { updateUserNameAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { ProfilePicture } from "./profile-picture";
@@ -30,7 +31,7 @@ export const ProfileSettings = ({
name: string;
image?: string;
}) => {
- const updateUserName = useSafeAction(updateUserNameAction);
+ const updateUserName = useMutation(mutationOptions(updateUserNameAction));
const form = useForm({
defaultValues: {
name,
@@ -45,7 +46,11 @@ export const ProfileSettings = ({
<form
onSubmit={handleSubmit(async (data) => {
if (data.name !== name) {
- await updateUserName.executeAsync({ name: data.name });
+ try {
+ await updateUserName.mutateAsync({ name: data.name });
+ } catch {
+ return;
+ }
}
reset(data);
})}
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-dialog.tsx
index 33d64af91..1126dc496 100644
--- a/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-dialog.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -15,6 +16,7 @@ import {
import { Field, FieldError, FieldGroup, FieldLabel } from "@rallly/ui/field";
import { Form } from "@rallly/ui/form";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import React from "react";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
@@ -23,7 +25,6 @@ import { setPasswordAction } from "@/features/auth/actions";
import { PasswordStrengthMeter } from "@/features/auth/components/password-strength-meter";
import { usePasswordValidationSchema } from "@/features/auth/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function SetupPasswordDialog({
trigger,
@@ -40,17 +41,19 @@ export function SetupPasswordDialog({
});
const { formState } = form;
- const setPassword = useSafeAction(setPasswordAction, {
- onSuccess: () => {
- form.reset();
- dialog.dismiss();
- toast.success(
- t("passwordSetSuccess", {
- defaultValue: "Your password has been set successfully",
- }),
- );
- },
- });
+ const setPassword = useMutation(
+ mutationOptions(setPasswordAction, {
+ onSuccess: () => {
+ form.reset();
+ dialog.dismiss();
+ toast.success(
+ t("passwordSetSuccess", {
+ defaultValue: "Your password has been set successfully",
+ }),
+ );
+ },
+ }),
+ );
return (
<Dialog
@@ -67,7 +70,9 @@ export function SetupPasswordDialog({
<Form {...form}>
<form
onSubmit={form.handleSubmit(async (data) => {
- await setPassword.executeAsync({ password: data.password });
+ try {
+ await setPassword.mutateAsync({ password: data.password });
+ } catch {}
})}
>
<DialogHeader>
diff --git a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
index 0aa306c4b..8bcb8384f 100644
--- a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
+++ b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
@@ -1,59 +1,57 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { acceptInviteAction } from "@/features/space/member/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export const AcceptInviteButton = ({ spaceId }: { spaceId: string }) => {
const { t } = useTranslation();
const router = useRouter();
- const acceptInvite = useSafeAction(acceptInviteAction);
+ // Accepting deletes the invite, so the action response re-renders this
+ // route as a 404 and unmounts the button. Hook-level callbacks still run.
+ const acceptInvite = useMutation(
+ mutationOptions(acceptInviteAction, {
+ onSuccess: (data) => {
+ if (data.ok) {
+ toast.success(
+ t("acceptInviteSuccess", {
+ defaultValue: "Successfully joined the space!",
+ }),
+ );
+ router.push("/");
+ return;
+ }
- // The result is handled from the promise rather than the hook's
- // onSuccess: accepting deletes the invite, so the action response
- // re-renders this route as a 404 and unmounts the button before
- // effect-driven callbacks get a chance to run.
- const handleClick = async () => {
- const result = await acceptInvite.executeAsync({ spaceId });
- const data = result?.data;
-
- if (data?.ok) {
- toast.success(
- t("acceptInviteSuccess", {
- defaultValue: "Successfully joined the space!",
- }),
- );
- router.push("/");
- return;
- }
-
- switch (data?.reason) {
- case "INVITE_NOT_FOUND":
- toast.error(
- t("acceptInviteNotFound", {
- defaultValue: "This invite is no longer valid",
- }),
- );
- break;
- case "NOT_ENOUGH_SEATS":
- toast.error(
- t("acceptInviteNotEnoughSeats", {
- defaultValue:
- "There are not enough seats available to join this space",
- }),
- );
- break;
- }
- };
+ switch (data.reason) {
+ case "INVITE_NOT_FOUND":
+ toast.error(
+ t("acceptInviteNotFound", {
+ defaultValue: "This invite is no longer valid",
+ }),
+ );
+ break;
+ case "NOT_ENOUGH_SEATS":
+ toast.error(
+ t("acceptInviteNotEnoughSeats", {
+ defaultValue:
+ "There are not enough seats available to join this space",
+ }),
+ );
+ break;
+ }
+ },
+ }),
+ );
return (
<Button
variant="primary"
- onClick={handleClick}
- loading={acceptInvite.isExecuting}
+ onClick={() => acceptInvite.mutate({ spaceId })}
+ loading={acceptInvite.isPending}
>
<Trans i18nKey="acceptInvite" defaults="Accept invite" />
</Button>
diff --git a/apps/web/src/app/[locale]/admin-setup/make-me-admin-button.tsx b/apps/web/src/app/[locale]/admin-setup/make-me-admin-button.tsx
index 5b752f406..7c759c22d 100644
--- a/apps/web/src/app/[locale]/admin-setup/make-me-admin-button.tsx
+++ b/apps/web/src/app/[locale]/admin-setup/make-me-admin-button.tsx
@@ -1,18 +1,17 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
+import { useMutation } from "@tanstack/react-query";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { makeMeAdminAction } from "./actions";
export function MakeMeAdminButton() {
- const makeMeAdmin = useSafeAction(makeMeAdminAction);
+ const makeMeAdmin = useMutation(mutationOptions(makeMeAdminAction));
return (
<Button
- onClick={async () => {
- await makeMeAdmin.executeAsync();
- }}
- loading={makeMeAdmin.isExecuting}
+ onClick={() => makeMeAdmin.mutate()}
+ loading={makeMeAdmin.isPending}
variant="primary"
>
<Trans i18nKey="adminSetupCta" defaults="Make me an admin" />
diff --git a/apps/web/src/app/[locale]/control-panel/branding/components/app-name-field.tsx b/apps/web/src/app/[locale]/control-panel/branding/components/app-name-field.tsx
index fb2139b74..adb386268 100644
--- a/apps/web/src/app/[locale]/control-panel/branding/components/app-name-field.tsx
+++ b/apps/web/src/app/[locale]/control-panel/branding/components/app-name-field.tsx
@@ -1,13 +1,14 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { FieldError } from "@rallly/ui/field";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { Controller, useForm } from "react-hook-form";
import { InputWithSaveButton } from "@/components/input-with-save-button";
import { brandingSettingsSchema } from "@/features/instance-settings/schema";
import { useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { updateBrandingSettingsAction } from "../actions";
const appNameSchema = brandingSettingsSchema.pick({ appName: true });
@@ -20,8 +21,6 @@ export function AppNameField({
disabled?: boolean;
}) {
const { t } = useTranslation();
- const updateBranding = useSafeAction(updateBrandingSettingsAction);
-
const form = useForm({
resolver: zodResolver(appNameSchema),
defaultValues: {
@@ -29,15 +28,19 @@ export function AppNameField({
},
});
+ const updateBranding = useMutation(
+ mutationOptions(updateBrandingSettingsAction, {
+ onSuccess: (_data, input) => {
+ form.reset(input);
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ },
+ }),
+ );
+
return (
<form
- onSubmit={form.handleSubmit(async (data) => {
- const result = await updateBranding.executeAsync(data);
-
- if (!result?.serverError && !result?.validationErrors) {
- form.reset(data);
- toast.success(t("saved", { defaultValue: "Saved" }));
- }
+ onSubmit={form.handleSubmit((data) => {
+ updateBranding.mutate(data);
})}
>
<Controller
@@ -51,7 +54,7 @@ export function AppNameField({
disabled={disabled}
aria-invalid={fieldState.invalid}
isDirty={form.formState.isDirty}
- isSaving={updateBranding.isExecuting}
+ isSaving={updateBranding.isPending}
/>
{fieldState.invalid ? (
<FieldError className="mt-1.5" errors={[fieldState.error]} />
diff --git a/apps/web/src/app/[locale]/control-panel/branding/components/hide-attribution-field.tsx b/apps/web/src/app/[locale]/control-panel/branding/components/hide-attribution-field.tsx
index d6b93fb36..f9a5dd72c 100644
--- a/apps/web/src/app/[locale]/control-panel/branding/components/hide-attribution-field.tsx
+++ b/apps/web/src/app/[locale]/control-panel/branding/components/hide-attribution-field.tsx
@@ -1,10 +1,11 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
+import { useMutation } from "@tanstack/react-query";
import React from "react";
import { useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { updateBrandingSettingsAction } from "../actions";
export function HideAttributionField({
@@ -15,7 +16,9 @@ export function HideAttributionField({
disabled?: boolean;
}) {
const { t } = useTranslation();
- const updateBranding = useSafeAction(updateBrandingSettingsAction);
+ const updateBranding = useMutation(
+ mutationOptions(updateBrandingSettingsAction),
+ );
// Optimistic value shown until the post-action router refresh delivers
// the updated settings; reverts automatically if the action fails.
@@ -25,13 +28,12 @@ export function HideAttributionField({
const handleToggle = (newChecked: boolean) => {
React.startTransition(async () => {
setOptimisticHideAttribution(newChecked);
- const result = await updateBranding.executeAsync({
- hideAttribution: newChecked,
- });
-
- if (!result?.serverError && !result?.validationErrors) {
- toast.success(t("saved", { defaultValue: "Saved" }));
+ try {
+ await updateBranding.mutateAsync({ hideAttribution: newChecked });
+ } catch {
+ return;
}
+ toast.success(t("saved", { defaultValue: "Saved" }));
});
};
@@ -40,7 +42,7 @@ export function HideAttributionField({
id="hide-attribution"
checked={hideAttribution}
onCheckedChange={handleToggle}
- disabled={disabled || updateBranding.isExecuting}
+ disabled={disabled || updateBranding.isPending}
/>
);
}
diff --git a/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx b/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx
index 3c1df4457..630a501eb 100644
--- a/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx
+++ b/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx
@@ -1,11 +1,12 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { cn } from "@rallly/ui";
+import { useMutation } from "@tanstack/react-query";
import { ImageUploadControl } from "@/components/image-upload";
import { LOGO_VIEWBOX } from "@/features/branding/constants";
import { brandingLogoProfiles } from "@/features/instance-settings/constants";
import type { BrandingLogoType } from "@/features/instance-settings/schema";
-import { useSafeAction } from "@/lib/safe-action/client";
import {
getBrandingLogoUploadUrlAction,
removeBrandingLogoAction,
@@ -46,9 +47,11 @@ export function LogoUploadField({
hasCustomLogo: boolean;
disabled?: boolean;
}) {
- const getLogoUploadUrl = useSafeAction(getBrandingLogoUploadUrlAction);
- const updateLogo = useSafeAction(updateBrandingLogoAction);
- const removeLogo = useSafeAction(removeBrandingLogoAction);
+ const getLogoUploadUrl = useMutation(
+ mutationOptions(getBrandingLogoUploadUrlAction),
+ );
+ const updateLogo = useMutation(mutationOptions(updateBrandingLogoAction));
+ const removeLogo = useMutation(mutationOptions(removeBrandingLogoAction));
return (
<div className="w-full space-y-3">
@@ -127,12 +130,14 @@ export function LogoUploadField({
profile={brandingLogoProfiles[logoType]}
disabled={disabled}
signUpload={(input) =>
- getLogoUploadUrl.executeAsync({ logoType, ...input })
+ getLogoUploadUrl.mutateAsync({ logoType, ...input })
}
persistUpload={(imageKey) =>
- updateLogo.executeAsync({ logoType, imageKey })
+ updateLogo.mutateAsync({ logoType, imageKey })
}
- onRemove={() => removeLogo.executeAsync({ logoType })}
+ // The global handler reports the failure; a rejection here would
+ // escape the remove transition.
+ onRemove={() => removeLogo.mutateAsync({ logoType }).catch(() => {})}
hasCurrentImage={hasCustomLogo}
/>
</div>
diff --git a/apps/web/src/app/[locale]/control-panel/branding/components/primary-color-field.tsx b/apps/web/src/app/[locale]/control-panel/branding/components/primary-color-field.tsx
index 31fa2a166..0efd27218 100644
--- a/apps/web/src/app/[locale]/control-panel/branding/components/primary-color-field.tsx
+++ b/apps/web/src/app/[locale]/control-panel/branding/components/primary-color-field.tsx
@@ -1,11 +1,12 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { parseColor } from "@rallly/ui/color-picker";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import React from "react";
import { ColorPickerWithSaveButton } from "@/components/color-picker-with-save-button";
import { useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { updateBrandingSettingsAction } from "../actions";
export function PrimaryColorField({
@@ -20,20 +21,22 @@ export function PrimaryColorField({
"aria-labelledby"?: string;
}) {
const { t } = useTranslation();
- const updateBranding = useSafeAction(updateBrandingSettingsAction);
+ const updateBranding = useMutation(
+ mutationOptions(updateBrandingSettingsAction, {
+ onSuccess: () => {
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ },
+ }),
+ );
const [color, setColor] = React.useState(() => parseColor(defaultValue));
const hexColor = color.toString("hex");
- const handleSave = async () => {
- const result = await updateBranding.executeAsync(
+ const handleSave = () => {
+ updateBranding.mutate(
field === "primaryColor"
? { primaryColor: hexColor }
: { primaryColorDark: hexColor },
);
-
- if (!result?.serverError && !result?.validationErrors) {
- toast.success(t("saved", { defaultValue: "Saved" }));
- }
};
return (
@@ -41,7 +44,7 @@ export function PrimaryColorField({
value={color}
onChange={setColor}
disabled={disabled}
- isSaving={updateBranding.isExecuting}
+ isSaving={updateBranding.isPending}
onSave={handleSave}
aria-labelledby={labelledBy}
/>
diff --git a/apps/web/src/app/[locale]/control-panel/settings/footer-links-field.tsx b/apps/web/src/app/[locale]/control-panel/settings/footer-links-field.tsx
index a355b1444..6e803c529 100644
--- a/apps/web/src/app/[locale]/control-panel/settings/footer-links-field.tsx
+++ b/apps/web/src/app/[locale]/control-panel/settings/footer-links-field.tsx
@@ -1,10 +1,12 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import { FieldError, FieldLabel } from "@rallly/ui/field";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { PlusIcon, Trash2Icon } from "lucide-react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import * as z from "zod";
@@ -16,7 +18,6 @@ import {
isValidFooterLinkHref,
} from "@/features/instance-settings/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { updateFooterLinksAction } from "./actions";
export function FooterLinksField({
@@ -25,8 +26,6 @@ export function FooterLinksField({
defaultValue: FooterLink[];
}) {
const { t } = useTranslation();
- const updateFooterLinks = useSafeAction(updateFooterLinksAction);
-
// Mirrors footerLinksSchema, with the href message translated. The server
// action still validates against the un-localised schema.
const formSchema = z.object({
@@ -60,6 +59,15 @@ export function FooterLinksField({
},
});
+ const updateFooterLinks = useMutation(
+ mutationOptions(updateFooterLinksAction, {
+ onSuccess: (_data, input) => {
+ form.reset(input);
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ },
+ }),
+ );
+
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "footerLinks",
@@ -68,13 +76,8 @@ export function FooterLinksField({
return (
<form
className="space-y-4"
- onSubmit={form.handleSubmit(async (data) => {
- const result = await updateFooterLinks.executeAsync(data);
-
- if (!result?.serverError && !result?.validationErrors) {
- form.reset(data);
- toast.success(t("saved", { defaultValue: "Saved" }));
- }
+ onSubmit={form.handleSubmit((data) => {
+ updateFooterLinks.mutate(data);
})}
>
{fields.length > 0 ? (
@@ -159,7 +162,7 @@ export function FooterLinksField({
</Button>
<Button
type="submit"
- loading={updateFooterLinks.isExecuting}
+ loading={updateFooterLinks.isPending}
disabled={!form.formState.isDirty}
>
<Trans i18nKey="save" defaults="Save" />
diff --git a/apps/web/src/app/[locale]/control-panel/settings/instance-settings-form.tsx b/apps/web/src/app/[locale]/control-panel/settings/instance-settings-form.tsx
index ab06e28d6..0d1347e73 100644
--- a/apps/web/src/app/[locale]/control-panel/settings/instance-settings-form.tsx
+++ b/apps/web/src/app/[locale]/control-panel/settings/instance-settings-form.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Alert, AlertDescription } from "@rallly/ui/alert";
import {
Field,
@@ -16,12 +17,12 @@ import {
SelectValue,
} from "@rallly/ui/select";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { ContainerIcon } from "lucide-react";
import React from "react";
import type { InstanceSettings } from "@/features/instance-settings/schema";
import { Trans, useTranslation } from "@/i18n/client";
import { useFeatureFlag } from "@/lib/feature-flags/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { updateInstanceSettingsAction } from "./actions";
export function InstanceSettingsForm({
@@ -34,20 +35,21 @@ export function InstanceSettingsForm({
!isRegistrationEnabled || Boolean(defaultValue.disableUserRegistration),
);
- const updateInstanceSettings = useSafeAction(updateInstanceSettingsAction);
+ const updateInstanceSettings = useMutation(
+ mutationOptions(updateInstanceSettingsAction),
+ );
const { t } = useTranslation();
const handleChange = (value: string) => {
const disabled = value === "disabled";
setDisableUserRegistration(disabled);
toast.promise(
- updateInstanceSettings.executeAsync({
+ updateInstanceSettings.mutateAsync({
disableUserRegistration: disabled,
}),
{
loading: t("saving", { defaultValue: "Saving..." }),
success: t("saved", { defaultValue: "Saved" }),
- error: t("unexpectedError", { defaultValue: "Unexpected error" }),
},
);
};
diff --git a/apps/web/src/app/[locale]/control-panel/users/actions.ts b/apps/web/src/app/[locale]/control-panel/users/actions.ts
index 255169e26..32c83f4f2 100644
--- a/apps/web/src/app/[locale]/control-panel/users/actions.ts
+++ b/apps/web/src/app/[locale]/control-panel/users/actions.ts
@@ -1,5 +1,7 @@
"use server";
+
import { subject } from "@casl/ability";
+import { refresh } from "next/cache";
import * as z from "zod";
import {
cancelUserSubscriptions,
@@ -52,6 +54,8 @@ export const deleteUserAction = adminActionClient
await hardDeleteUser({ userId });
+ refresh();
+
return {
success: true,
};
@@ -97,4 +101,6 @@ export const banUserAction = adminActionClient
userId,
reason: reason || "Banned from the control panel",
});
+
+ refresh();
});
diff --git a/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx b/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx
index d1b7ebe6d..c473ead85 100644
--- a/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx
+++ b/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -19,10 +20,10 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Textarea } from "@rallly/ui/textarea";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { banUserAction } from "../actions";
const useSchema = () => {
@@ -58,11 +59,13 @@ export function BanUserDialog({
},
});
- const banUser = useSafeAction(banUserAction, {
- onSuccess: () => {
- onOpenChange(false);
- },
- });
+ const banUser = useMutation(
+ mutationOptions(banUserAction, {
+ onSuccess: () => {
+ onOpenChange(false);
+ },
+ }),
+ );
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -84,8 +87,8 @@ export function BanUserDialog({
</DialogHeader>
<Form {...form}>
<form
- onSubmit={form.handleSubmit(async (data) => {
- await banUser.executeAsync({
+ onSubmit={form.handleSubmit((data) => {
+ banUser.mutate({
userId,
reason: data.reason || undefined,
});
@@ -115,7 +118,7 @@ export function BanUserDialog({
</DialogClose>
<Button
variant="destructive"
- loading={banUser.isExecuting}
+ loading={banUser.isPending}
type="submit"
>
<Trans i18nKey="banUser" defaults="Ban user" />
diff --git a/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx b/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx
index 18c9aa13a..22bf1a7c4 100644
--- a/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx
+++ b/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -20,10 +21,10 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { deleteUserAction } from "../actions";
const useSchema = (email: string) => {
@@ -58,11 +59,13 @@ export function DeleteUserDialog({
},
});
- const deleteUser = useSafeAction(deleteUserAction, {
- onSuccess: () => {
- onOpenChange(false);
- },
- });
+ const deleteUser = useMutation(
+ mutationOptions(deleteUserAction, {
+ onSuccess: () => {
+ onOpenChange(false);
+ },
+ }),
+ );
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -80,8 +83,8 @@ export function DeleteUserDialog({
</DialogHeader>
<Form {...form}>
<form
- onSubmit={form.handleSubmit(async () => {
- await deleteUser.executeAsync({ userId });
+ onSubmit={form.handleSubmit(() => {
+ deleteUser.mutate({ userId });
})}
>
<FormField
@@ -115,7 +118,7 @@ export function DeleteUserDialog({
</DialogClose>
<Button
variant="destructive"
- loading={deleteUser.isExecuting}
+ loading={deleteUser.isPending}
type="submit"
>
<Trans i18nKey="delete" defaults="Delete" />
diff --git a/apps/web/src/app/[locale]/control-panel/users/user-row.tsx b/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
index 36373abf3..51278b253 100644
--- a/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
+++ b/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
@@ -1,4 +1,5 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { cn } from "@rallly/ui";
import { Badge } from "@rallly/ui/badge";
import { Button } from "@rallly/ui/button";
@@ -15,6 +16,7 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
+import { useMutation } from "@tanstack/react-query";
import {
BanIcon,
MoreHorizontal,
@@ -22,13 +24,11 @@ import {
UserCheckIcon,
UserPenIcon,
} from "lucide-react";
-import { useTransition } from "react";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { StackedListItem } from "@/components/stacked-list";
import { changeRoleAction, unbanUserAction } from "@/features/user/actions";
import { userRoleSchema } from "@/features/user/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { BanUserDialog } from "./dialogs/ban-user-dialog";
import { DeleteUserDialog } from "./dialogs/delete-user-dialog";
@@ -54,10 +54,10 @@ export function UserRow({
canDelete: boolean;
}) {
const { t } = useTranslation();
- const changeRole = useSafeAction(changeRoleAction);
- const unbanUser = useSafeAction(unbanUserAction);
+ const changeRole = useMutation(mutationOptions(changeRoleAction));
+ const unbanUser = useMutation(mutationOptions(unbanUserAction));
- const [isPending, startTransition] = useTransition();
+ const isPending = changeRole.isPending || unbanUser.isPending;
const deleteDialog = useDialog();
const banDialog = useDialog();
@@ -105,12 +105,10 @@ export function UserRow({
<DropdownMenuSubContent>
<DropdownMenuRadioGroup
value={role}
- onValueChange={async (value) => {
- startTransition(async () => {
- await changeRole.executeAsync({
- role: userRoleSchema.parse(value),
- userId,
- });
+ onValueChange={(value) => {
+ changeRole.mutate({
+ role: userRoleSchema.parse(value),
+ userId,
});
}}
>
@@ -127,9 +125,7 @@ export function UserRow({
{banned ? (
<DropdownMenuItem
onClick={() => {
- startTransition(async () => {
- await unbanUser.executeAsync({ userId });
- });
+ unbanUser.mutate({ userId });
}}
disabled={!canBan}
>
diff --git a/apps/web/src/app/[locale]/e/[id]/components/registration-form.tsx b/apps/web/src/app/[locale]/e/[id]/components/registration-form.tsx
index e73a7ff5d..41e7794d0 100644
--- a/apps/web/src/app/[locale]/e/[id]/components/registration-form.tsx
+++ b/apps/web/src/app/[locale]/e/[id]/components/registration-form.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Form,
@@ -11,11 +12,11 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { submitRsvpAction } from "@/features/scheduled-event/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
const formSchema = z.object({
name: z.string().trim().min(1).max(100),
@@ -30,7 +31,6 @@ export function RegistrationForm({
onSuccess: (registration: { name: string; email: string }) => void;
}) {
const { t } = useTranslation();
- const submitRsvp = useSafeAction(submitRsvpAction);
const form = useForm({
defaultValues: {
name: "",
@@ -38,31 +38,34 @@ export function RegistrationForm({
},
resolver: zodResolver(formSchema),
});
+ const submitRsvp = useMutation(
+ mutationOptions(submitRsvpAction, {
+ onSuccess: (data, input) => {
+ if (!data.ok) {
+ form.setError("email", {
+ message: t("eventRegisterAlreadyResponded", {
+ defaultValue: "This email has already been used to respond",
+ }),
+ });
+ return;
+ }
+
+ onSuccess({ name: input.name, email: input.email });
+ },
+ }),
+ );
return (
<Form {...form}>
<form
className="grid gap-4"
- onSubmit={form.handleSubmit(async (data) => {
- const result = await submitRsvp.executeAsync({
+ onSubmit={form.handleSubmit((data) => {
+ submitRsvp.mutate({
eventId,
name: data.name,
email: data.email,
status: "accepted",
});
-
- if (result.data?.ok === false) {
- form.setError("email", {
- message: t("eventRegisterAlreadyResponded", {
- defaultValue: "This email has already been used to respond",
- }),
- });
- return;
- }
-
- if (result.data?.ok) {
- onSuccess({ name: data.name, email: data.email });
- }
})}
>
<FormField
@@ -76,7 +79,7 @@ export function RegistrationForm({
<Input
autoFocus
autoComplete="name"
- disabled={form.formState.isSubmitting}
+ disabled={submitRsvp.isPending}
placeholder={t("namePlaceholder", {
defaultValue: "Jessie Smith",
})}
@@ -98,7 +101,7 @@ export function RegistrationForm({
<Input
type="email"
autoComplete="email"
- disabled={form.formState.isSubmitting}
+ disabled={submitRsvp.isPending}
placeholder={t("emailPlaceholder", {
defaultValue: "[email protected]",
})}
@@ -113,7 +116,7 @@ export function RegistrationForm({
size="lg"
variant="primary"
type="submit"
- loading={form.formState.isSubmitting}
+ loading={submitRsvp.isPending}
>
<Trans i18nKey="register" defaults="Register" />
</Button>
diff --git a/apps/web/src/app/[locale]/e/[id]/components/rsvp-cancel.tsx b/apps/web/src/app/[locale]/e/[id]/components/rsvp-cancel.tsx
index e511f3960..b295847fb 100644
--- a/apps/web/src/app/[locale]/e/[id]/components/rsvp-cancel.tsx
+++ b/apps/web/src/app/[locale]/e/[id]/components/rsvp-cancel.tsx
@@ -1,13 +1,12 @@
"use client";
-import { useRouter } from "next/navigation";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
+import { useMutation } from "@tanstack/react-query";
import { cancelRsvpAction } from "@/features/scheduled-event/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function RsvpCancel({ inviteUid }: { inviteUid: string }) {
- const router = useRouter();
- const cancelRsvp = useSafeAction(cancelRsvpAction);
+ const cancelRsvp = useMutation(mutationOptions(cancelRsvpAction));
return (
<p className="text-muted-foreground text-sm">
@@ -18,14 +17,10 @@ export function RsvpCancel({ inviteUid }: { inviteUid: string }) {
a: (
<button
type="button"
- disabled={cancelRsvp.isExecuting}
+ disabled={cancelRsvp.isPending}
className="underline hover:text-foreground"
- onClick={async () => {
- await cancelRsvp.executeAsync({ inviteUid });
- // Re-run the server query so the card reflects the
- // cancellation (a not_found result means it's already gone
- // server-side, so refreshing is correct either way).
- router.refresh();
+ onClick={() => {
+ cancelRsvp.mutate({ inviteUid });
}}
/>
),
diff --git a/apps/web/src/app/[locale]/e/[id]/components/rsvp-one-click-register.tsx b/apps/web/src/app/[locale]/e/[id]/components/rsvp-one-click-register.tsx
index 045180f4d..76c21af5a 100644
--- a/apps/web/src/app/[locale]/e/[id]/components/rsvp-one-click-register.tsx
+++ b/apps/web/src/app/[locale]/e/[id]/components/rsvp-one-click-register.tsx
@@ -1,10 +1,11 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
+import { useMutation } from "@tanstack/react-query";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { registerForEventAction } from "@/features/scheduled-event/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function RsvpOneClickRegister({
eventId,
@@ -17,7 +18,7 @@ export function RsvpOneClickRegister({
email: string;
image?: string;
}) {
- const register = useSafeAction(registerForEventAction);
+ const register = useMutation(mutationOptions(registerForEventAction));
return (
<div className="flex flex-col gap-3">
@@ -31,9 +32,9 @@ export function RsvpOneClickRegister({
<Button
size="lg"
variant="primary"
- loading={register.isExecuting}
- onClick={async () => {
- await register.executeAsync({ eventId });
+ loading={register.isPending}
+ onClick={() => {
+ register.mutate({ eventId });
}}
>
<Trans i18nKey="rsvpOneClickRegister" defaults="One-click register" />
diff --git a/apps/web/src/app/[locale]/setup/actions.ts b/apps/web/src/app/[locale]/setup/actions.ts
index 8102fc2dd..7fe53f9bf 100644
--- a/apps/web/src/app/[locale]/setup/actions.ts
+++ b/apps/web/src/app/[locale]/setup/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { refresh } from "next/cache";
+
import { headers } from "next/headers";
import * as z from "zod";
import { adoptOrphanedPolls } from "@/features/poll/mutations";
@@ -64,6 +66,7 @@ export const setupSpaceAction = authActionClient
userId: ctx.user.id,
spaceId: ownedSpace.id,
});
+ refresh();
return;
}
@@ -142,4 +145,6 @@ export const setupSpaceAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
diff --git a/apps/web/src/app/[locale]/setup/components/setup-form.tsx b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
index 6d532be15..e2e192a77 100644
--- a/apps/web/src/app/[locale]/setup/components/setup-form.tsx
+++ b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import { ButtonGroup, ButtonGroupItem } from "@rallly/ui/button-group";
@@ -14,6 +15,7 @@ import {
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
+import { useMutation } from "@tanstack/react-query";
import { BriefcaseIcon, UserIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
@@ -30,7 +32,6 @@ import { authClient } from "@/lib/auth-client";
import { getLocaleDefaults } from "@/lib/datetime/locales";
import type { TimeFormat } from "@/lib/datetime/types";
import { useLocale } from "@/lib/locale/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
function useSetupFormSchema() {
@@ -106,7 +107,7 @@ export function SetupForm({
const { t } = useTranslation();
const { locale } = useLocale();
const schema = useSetupFormSchema();
- const setupSpace = useSafeAction(setupSpaceAction);
+ const setupSpace = useMutation(mutationOptions(setupSpaceAction));
const form = useForm({
resolver: zodResolver(schema),
@@ -167,20 +168,22 @@ export function SetupForm({
return;
}
- // Server errors surface through the global useSafeAction toast;
- // the button unlocks (hasSucceeded stays false) so the user can
- // retry. On success the hook refreshes the router and the page
- // redirects onward while the button stays loading.
- await setupSpace.executeAsync(
- spaceType === "work"
- ? {
- spaceType,
- organizationName: organizationName.trim(),
- industry: industry ?? undefined,
- jobTitle: jobTitle ?? undefined,
- }
- : { spaceType },
- );
+ // Server errors surface through the global mutation toast; the
+ // button unlocks (isSuccess stays false) so the user can retry.
+ // On success the action refreshes the page, which redirects
+ // onward while the button stays loading.
+ try {
+ await setupSpace.mutateAsync(
+ spaceType === "work"
+ ? {
+ spaceType,
+ organizationName: organizationName.trim(),
+ industry: industry ?? undefined,
+ jobTitle: jobTitle ?? undefined,
+ }
+ : { spaceType },
+ );
+ } catch {}
},
)}
className="space-y-4"
@@ -387,7 +390,7 @@ export function SetupForm({
type="submit"
variant="primary"
size="lg"
- loading={form.formState.isSubmitting || setupSpace.hasSucceeded}
+ loading={form.formState.isSubmitting || setupSpace.isSuccess}
className="w-full"
>
<Trans i18nKey="continue" defaults="Continue" />
diff --git a/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx b/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx
index b52ee7ce3..14c693ee2 100644
--- a/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx
+++ b/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx
@@ -1,13 +1,14 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { buttonVariants } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
+import { useMutation } from "@tanstack/react-query";
import { BellOffIcon } from "lucide-react";
import React from "react";
import { Link } from "@/components/link";
import { unsubscribeWithTokenAction } from "@/features/notifications/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function MutePollForm({
token,
@@ -21,13 +22,15 @@ export function MutePollForm({
initialMuted: boolean;
}) {
const [muted, setMuted] = React.useState(initialMuted);
- const unsubscribe = useSafeAction(unsubscribeWithTokenAction, {
- onSuccess: ({ data }) => {
- if (data?.ok) {
- setMuted(true);
- }
- },
- });
+ const unsubscribe = useMutation(
+ mutationOptions(unsubscribeWithTokenAction, {
+ onSuccess: (data) => {
+ if (data.ok) {
+ setMuted(true);
+ }
+ },
+ }),
+ );
if (muted) {
return (
@@ -84,8 +87,8 @@ export function MutePollForm({
<div className="flex flex-col gap-2">
<Button
variant="primary"
- loading={unsubscribe.isExecuting}
- onClick={() => unsubscribe.execute({ token })}
+ loading={unsubscribe.isPending}
+ onClick={() => unsubscribe.mutate({ token })}
>
<Trans i18nKey="muteNotifications" defaults="Mute notifications" />
</Button>
diff --git a/apps/web/src/components/asset-upload/use-asset-upload.ts b/apps/web/src/components/asset-upload/use-asset-upload.ts
index e46241965..2920dbc8c 100644
--- a/apps/web/src/components/asset-upload/use-asset-upload.ts
+++ b/apps/web/src/components/asset-upload/use-asset-upload.ts
@@ -1,36 +1,14 @@
"use client";
+import {
+ hasServerError,
+ isActionMutationError,
+} from "@next-safe-action/adapter-tanstack-query";
import { toast } from "@rallly/ui/sonner";
import React from "react";
import { useTranslation } from "@/i18n/client";
import { uploadAsset } from "@/lib/storage/upload-client";
-/**
- * A safe-action result, structurally. Actions resolve (rather than reject)
- * on server errors, so success has to be read off the result — forgetting
- * that check is the bug class this hook exists to remove.
- */
-interface ActionResult<T> {
- data?: T;
- serverError?: unknown;
- validationErrors?: unknown;
-}
-
-/**
- * Server errors already surface a toast via useSafeAction's global handler;
- * this marker keeps the hook from toasting the same failure twice.
- */
-class ActionFailedError extends Error {}
-
-function assertActionOk(result: ActionResult<unknown> | undefined) {
- if (result?.serverError) {
- throw new ActionFailedError("Action failed");
- }
- if (!result || result.validationErrors) {
- throw new Error("Action failed");
- }
-}
-
/**
* The two-phase upload protocol, once: sign against the slot's profile,
* PUT the bytes, persist the key. Any failed step aborts the pipeline and
@@ -47,46 +25,49 @@ export function useAssetUpload<TAccept extends string>({
signUpload: (input: {
fileType: TAccept;
fileSize: number;
- }) => Promise<ActionResult<{ url: string; key: string }> | undefined>;
- persistUpload: (key: string) => Promise<ActionResult<unknown> | undefined>;
+ }) => Promise<{ url: string; key: string }>;
+ persistUpload: (key: string) => Promise<unknown>;
}) {
const { t } = useTranslation();
const [isUploading, startUploading] = React.useTransition();
+ const showUploadError = () => {
+ toast.error(
+ t("assetUploadError", {
+ defaultValue: "Failed to upload",
+ }),
+ {
+ description: t("assetUploadErrorDescription", {
+ defaultValue:
+ "There was an issue uploading your file. Please try again later.",
+ }),
+ },
+ );
+ };
+
const upload = (file: File, options?: { onSuccess?: () => void }) => {
startUploading(async () => {
try {
- const signResult = await signUpload({
+ const signedUpload = await signUpload({
fileType: file.type as TAccept,
fileSize: file.size,
});
- assertActionOk(signResult);
-
- const signedUpload = signResult?.data;
-
- if (!signedUpload) {
- throw new Error("Failed to get upload URL");
+ try {
+ await uploadAsset({ url: signedUpload.url, file });
+ } catch {
+ showUploadError();
+ return;
}
- await uploadAsset({ url: signedUpload.url, file });
-
- assertActionOk(await persistUpload(signedUpload.key));
+ await persistUpload(signedUpload.key);
options?.onSuccess?.();
} catch (error) {
- if (!(error instanceof ActionFailedError)) {
- toast.error(
- t("assetUploadError", {
- defaultValue: "Failed to upload",
- }),
- {
- description: t("assetUploadErrorDescription", {
- defaultValue:
- "There was an issue uploading your file. Please try again later.",
- }),
- },
- );
+ // The mutation cache toasts server errors and failed requests;
+ // only validation errors are left to report here
+ if (isActionMutationError(error) && !hasServerError(error)) {
+ showUploadError();
}
}
});
diff --git a/apps/web/src/features/api-keys/actions.ts b/apps/web/src/features/api-keys/actions.ts
index 2307eacb9..9b861a475 100644
--- a/apps/web/src/features/api-keys/actions.ts
+++ b/apps/web/src/features/api-keys/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { refresh } from "next/cache";
+
import { isApiAccessEnabled } from "@/features/api-keys/data";
import { createApiKey, revokeApiKey } from "@/features/api-keys/mutations";
import {
@@ -63,6 +65,8 @@ export const createApiKeyAction = authActionClient
});
}
+ refresh();
+
return result;
});
@@ -80,4 +84,6 @@ export const revokeApiKeyAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
diff --git a/apps/web/src/features/auth/actions.ts b/apps/web/src/features/auth/actions.ts
index 469c4d67e..9ca8a18d1 100644
--- a/apps/web/src/features/auth/actions.ts
+++ b/apps/web/src/features/auth/actions.ts
@@ -1,5 +1,7 @@
"use server";
+
import { sendPasswordAddedEmail } from "@rallly/emails/templates/password-added";
+import { refresh } from "next/cache";
import { headers } from "next/headers";
import { after } from "next/server";
import * as z from "zod";
@@ -78,6 +80,8 @@ export const setPasswordAction = authActionClient
user: ctx.user,
password: parsedInput.password,
});
+
+ refresh();
});
// Other sessions are deliberately NOT revoked: adding a first credential is
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
index d4170258c..0f79ff7e1 100644
--- a/apps/web/src/features/billing/actions.ts
+++ b/apps/web/src/features/billing/actions.ts
@@ -2,6 +2,7 @@
import { displayedCurrencies, getProPricing } from "@rallly/billing";
import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { refresh } from "next/cache";
import { redirect } from "next/navigation";
import * as z from "zod";
import { getProPrices, getSpaceSubscription } from "@/features/billing/data";
@@ -314,6 +315,8 @@ export const resumePlanAction = authActionClient
properties: { interval: subscription.interval },
groups: { space: space.id },
});
+
+ refresh();
});
export const openBillingDetailsAction = authActionClient
diff --git a/apps/web/src/features/billing/components/upgrade-button.tsx b/apps/web/src/features/billing/components/upgrade-button.tsx
index 960ea1786..5f8ef1316 100644
--- a/apps/web/src/features/billing/components/upgrade-button.tsx
+++ b/apps/web/src/features/billing/components/upgrade-button.tsx
@@ -1,13 +1,14 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import type { DisplayedCurrency } from "@rallly/billing";
import { Button } from "@rallly/ui/button";
+import { useMutation } from "@tanstack/react-query";
import { usePathname, useRouter } from "next/navigation";
import type React from "react";
import { upgradeToProAction } from "@/features/billing/actions";
import { useUser } from "@/features/user/client";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export const UpgradeButton = ({
children,
@@ -24,7 +25,7 @@ export const UpgradeButton = ({
const pathname = usePathname();
const router = useRouter();
const { user } = useUser();
- const upgradeToPro = useSafeAction(upgradeToProAction);
+ const upgradeToPro = useMutation(mutationOptions(upgradeToProAction));
return (
<Button
@@ -32,14 +33,14 @@ export const UpgradeButton = ({
size="xl"
className={className}
variant="primary"
- loading={upgradeToPro.isExecuting}
+ loading={upgradeToPro.isPending}
onClick={() => {
onClick?.();
if (!user || user.isGuest) {
router.push(`/register?redirectTo=${encodeURIComponent(pathname)}`);
return;
}
- upgradeToPro.execute({
+ upgradeToPro.mutate({
period: annual ? "yearly" : "monthly",
currency,
returnPath: pathname,
diff --git a/apps/web/src/features/feedback/components/feedback-dialog.tsx b/apps/web/src/features/feedback/components/feedback-dialog.tsx
index 23417bfa6..f708a313e 100644
--- a/apps/web/src/features/feedback/components/feedback-dialog.tsx
+++ b/apps/web/src/features/feedback/components/feedback-dialog.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
import {
@@ -12,18 +13,18 @@ import {
} from "@rallly/ui/dialog";
import { Form, FormField, FormItem, FormMessage } from "@rallly/ui/form";
import { Textarea } from "@rallly/ui/textarea";
+import { useMutation } from "@tanstack/react-query";
import { CheckCircle2Icon } from "lucide-react";
import { useForm } from "react-hook-form";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { submitFeedbackAction } from "../actions";
import { isFeedbackEnabled } from "../constants";
import { feedbackSchema } from "../schema";
export function FeedbackDialog(props: DialogProps) {
const { t } = useTranslation();
- const submitFeedback = useSafeAction(submitFeedbackAction);
+ const submitFeedback = useMutation(mutationOptions(submitFeedbackAction));
const form = useForm({
resolver: zodResolver(feedbackSchema),
});
@@ -35,7 +36,7 @@ export function FeedbackDialog(props: DialogProps) {
return (
<Dialog {...props}>
<DialogContent>
- {!submitFeedback.hasSucceeded ? (
+ {!submitFeedback.isSuccess ? (
<>
<DialogHeader>
<DialogTitle>
@@ -51,8 +52,8 @@ export function FeedbackDialog(props: DialogProps) {
<Form {...form}>
<form
- onSubmit={form.handleSubmit(async (data) => {
- await submitFeedback.executeAsync(data);
+ onSubmit={form.handleSubmit((data) => {
+ submitFeedback.mutate(data);
})}
>
<FormField
@@ -61,7 +62,7 @@ export function FeedbackDialog(props: DialogProps) {
render={({ field }) => (
<FormItem>
<Textarea
- disabled={form.formState.isSubmitting}
+ disabled={submitFeedback.isPending}
className="w-full"
rows={5}
{...field}
@@ -75,7 +76,7 @@ export function FeedbackDialog(props: DialogProps) {
/>
<Button
type="submit"
- loading={form.formState.isSubmitting}
+ loading={submitFeedback.isPending}
className="mt-6"
variant="primary"
>
diff --git a/apps/web/src/features/licensing/components/license-key-form.tsx b/apps/web/src/features/licensing/components/license-key-form.tsx
index 1bdbb0844..72c0726fe 100644
--- a/apps/web/src/features/licensing/components/license-key-form.tsx
+++ b/apps/web/src/features/licensing/components/license-key-form.tsx
@@ -1,6 +1,10 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ isActionMutationError,
+ mutationOptions,
+} from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Form,
@@ -11,12 +15,11 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
-import { useRouter } from "next/navigation";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { validateLicenseKeyAction } from "@/features/licensing/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { checkLicenseKey } from "../utils";
const formSchema = z.object({
@@ -27,7 +30,6 @@ const formSchema = z.object({
export function LicenseKeyForm({ onSuccess }: { onSuccess?: () => void }) {
const { t } = useTranslation();
- const router = useRouter();
const form = useForm({
defaultValues: {
licenseKey: "",
@@ -35,41 +37,32 @@ export function LicenseKeyForm({ onSuccess }: { onSuccess?: () => void }) {
resolver: zodResolver(formSchema),
});
- const validateLicenseKey = useSafeAction(validateLicenseKeyAction);
+ const validateLicenseKey = useMutation(
+ mutationOptions(validateLicenseKeyAction, {
+ onSuccess: () => {
+ onSuccess?.();
+ },
+ onError: (error) => {
+ form.setError("licenseKey", {
+ message: isActionMutationError(error)
+ ? t("licenseKeyErrorInvalidLicenseKey", {
+ defaultValue: "Invalid license key",
+ })
+ : t("licenseKeyGenericError", {
+ defaultValue:
+ "An error occurred while validating the license key",
+ }),
+ });
+ },
+ }),
+ );
return (
<Form {...form}>
<form
className="space-y-4"
- onSubmit={form.handleSubmit(async (data) => {
- try {
- const result = await validateLicenseKey.executeAsync({
- key: data.licenseKey,
- });
-
- if (!result.data) {
- form.setError("licenseKey", {
- message: t("licenseKeyErrorInvalidLicenseKey", {
- defaultValue: "Invalid license key",
- }),
- });
- return;
- }
- } catch (_error) {
- form.setError("licenseKey", {
- message: t("licenseKeyGenericError", {
- defaultValue:
- "An error occurred while validating the license key",
- }),
- });
- return;
- }
-
- // Refreshing swaps the page to the installed-license branch, which
- // unmounts this form. Notify the owner first so closing the dialog
- // doesn't depend on that re-render winning a race.
- onSuccess?.();
- router.refresh();
+ onSubmit={form.handleSubmit((data) => {
+ validateLicenseKey.mutate({ key: data.licenseKey });
})}
>
<FormField
@@ -83,7 +76,7 @@ export function LicenseKeyForm({ onSuccess }: { onSuccess?: () => void }) {
<FormControl>
<Input
className="font-mono"
- disabled={form.formState.isSubmitting}
+ disabled={validateLicenseKey.isPending}
placeholder="RLYV4-XXXX-XXXX-XXXX-XXXX-XXXX"
{...field}
/>
@@ -97,7 +90,7 @@ export function LicenseKeyForm({ onSuccess }: { onSuccess?: () => void }) {
<div className="flex gap-2">
<Button
variant="primary"
- loading={form.formState.isSubmitting}
+ loading={validateLicenseKey.isPending}
type="submit"
>
<Trans i18nKey="activate" defaults="Activate" />
diff --git a/apps/web/src/features/licensing/components/refresh-license-button.tsx b/apps/web/src/features/licensing/components/refresh-license-button.tsx
index 99e7e459a..5a52c498b 100644
--- a/apps/web/src/features/licensing/components/refresh-license-button.tsx
+++ b/apps/web/src/features/licensing/components/refresh-license-button.tsx
@@ -1,14 +1,17 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
+import { useMutation } from "@tanstack/react-query";
import { RefreshCwIcon } from "lucide-react";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { refreshInstanceLicenseAction } from "../actions";
export function RefreshLicenseButton() {
- const refreshInstanceLicense = useSafeAction(refreshInstanceLicenseAction);
+ const refreshInstanceLicense = useMutation(
+ mutationOptions(refreshInstanceLicenseAction),
+ );
return (
<Tooltip>
@@ -16,8 +19,8 @@ export function RefreshLicenseButton() {
render={
<Button
variant="ghost"
- loading={refreshInstanceLicense.isExecuting}
- onClick={async () => await refreshInstanceLicense.executeAsync()}
+ loading={refreshInstanceLicense.isPending}
+ onClick={() => refreshInstanceLicense.mutate()}
>
<RefreshCwIcon className="text-muted-foreground" />
<span className="sr-only">
diff --git a/apps/web/src/features/licensing/components/remove-license-button.tsx b/apps/web/src/features/licensing/components/remove-license-button.tsx
index f6e8fb7a8..66b111d33 100644
--- a/apps/web/src/features/licensing/components/remove-license-button.tsx
+++ b/apps/web/src/features/licensing/components/remove-license-button.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -12,18 +13,19 @@ import {
DialogTrigger,
useDialog,
} from "@rallly/ui/dialog";
-
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
+import { useMutation } from "@tanstack/react-query";
import { XIcon } from "lucide-react";
import { useTransition } from "react";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { removeInstanceLicenseAction } from "../actions";
export function RemoveLicenseButton() {
const [isPending, startTransition] = useTransition();
const dialog = useDialog();
- const removeInstanceLicense = useSafeAction(removeInstanceLicenseAction);
+ const removeInstanceLicense = useMutation(
+ mutationOptions(removeInstanceLicenseAction),
+ );
return (
<Dialog {...dialog.dialogProps}>
<Tooltip>
@@ -66,7 +68,12 @@ export function RemoveLicenseButton() {
variant="destructive"
onClick={() =>
startTransition(async () => {
- await removeInstanceLicense.executeAsync();
+ try {
+ await removeInstanceLicense.mutateAsync();
+ } catch {
+ // The mutation cache toasts the error; keep the dialog open to retry
+ return;
+ }
dialog.dismiss();
})
}
diff --git a/apps/web/src/features/notifications/actions.ts b/apps/web/src/features/notifications/actions.ts
index 575a2267e..7a1a54456 100644
--- a/apps/web/src/features/notifications/actions.ts
+++ b/apps/web/src/features/notifications/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { refresh } from "next/cache";
+
import {
unsubscribeWithToken,
updateNotificationPreference,
@@ -28,6 +30,8 @@ export const updateNotificationPreferenceAction = authActionClient
enabled: parsedInput.enabled,
},
});
+
+ refresh();
});
// Public: the signed token is the credential, verified in the mutation.
@@ -35,5 +39,9 @@ export const unsubscribeWithTokenAction = actionClient
.metadata({ actionName: "unsubscribe_with_token" })
.inputSchema(unsubscribeWithTokenSchema)
.action(async ({ parsedInput }) => {
- return unsubscribeWithToken({ token: parsedInput.token });
+ const result = await unsubscribeWithToken({ token: parsedInput.token });
+
+ refresh();
+
+ return result;
});
diff --git a/apps/web/src/features/poll/actions.ts b/apps/web/src/features/poll/actions.ts
index d757e3eb8..3b7ba6abf 100644
--- a/apps/web/src/features/poll/actions.ts
+++ b/apps/web/src/features/poll/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { refresh } from "next/cache";
+
import { setPollMuted } from "@/features/poll/mutations";
import { setPollMutedSchema } from "@/features/poll/schema";
import { identifyGroup } from "@/lib/posthog";
@@ -27,5 +29,7 @@ export const setPollMutedAction = authActionClient
});
}
+ refresh();
+
return result;
});
diff --git a/apps/web/src/features/poll/components/invite-by-email.tsx b/apps/web/src/features/poll/components/invite-by-email.tsx
index 2af7fc37d..38e5282f7 100644
--- a/apps/web/src/features/poll/components/invite-by-email.tsx
+++ b/apps/web/src/features/poll/components/invite-by-email.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import {
@@ -9,6 +10,7 @@ import {
InputGroupInput,
} from "@rallly/ui/input-group";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { MailIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
@@ -35,7 +37,6 @@ import { sendPollInviteAction } from "@/features/poll/invite/actions";
import { sendPollInviteSchema } from "@/features/poll/invite/schema";
import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { trpc } from "@/trpc/client";
type Row = {
@@ -125,59 +126,57 @@ export function InviteByEmail() {
count,
});
- const sendInvite = useSafeAction(sendPollInviteAction, {
- onSuccess: async ({ data, input }) => {
- if (!data) {
+ const sendInvite = useMutation(
+ mutationOptions(sendPollInviteAction, {
+ onSuccess: (data, input) => {
+ if (data.ok) {
+ announce(
+ t("shareDialogInviteSent", {
+ defaultValue: "Invite sent to {email}",
+ email: input.email,
+ }),
+ );
+ return;
+ }
setSending((prev) => prev.filter((address) => address !== input.email));
- return;
- }
- if (data.ok) {
- announce(
- t("shareDialogInviteSent", {
- defaultValue: "Invite sent to {email}",
+ const messages = {
+ alreadyInvited: t("shareDialogAlreadyInvited", {
+ defaultValue: "{email} is already invited",
email: input.email,
}),
- );
- return;
- }
- setSending((prev) => prev.filter((address) => address !== input.email));
- const messages = {
- alreadyInvited: t("shareDialogAlreadyInvited", {
- defaultValue: "{email} is already invited",
- email: input.email,
- }),
- alreadyResponded: t("shareDialogAlreadyResponded", {
- defaultValue: "{email} has already responded",
- email: input.email,
- }),
- dailyLimit: t("shareDialogDailyLimit", {
- defaultValue: "You've reached today's limit of 100 invites",
- }),
- pollClosed: t("shareDialogPollClosed", {
- defaultValue: "Reopen the poll to send invites",
- }),
- sendFailed: t("shareDialogSendFailed", {
- defaultValue: "Couldn't send to {email}. Try again.",
- email: input.email,
- }),
- notFound: t("actionErrorNotFound", {
- defaultValue: "The resource was not found",
- }),
- paymentRequired: t("actionErrorPaymentRequired", {
- defaultValue: "You need to upgrade to perform this action",
- }),
- };
- toast.error(messages[data.reason]);
- announce(messages[data.reason]);
- if (data.reason === "sendFailed") {
+ alreadyResponded: t("shareDialogAlreadyResponded", {
+ defaultValue: "{email} has already responded",
+ email: input.email,
+ }),
+ dailyLimit: t("shareDialogDailyLimit", {
+ defaultValue: "You've reached today's limit of 100 invites",
+ }),
+ pollClosed: t("shareDialogPollClosed", {
+ defaultValue: "Reopen the poll to send invites",
+ }),
+ sendFailed: t("shareDialogSendFailed", {
+ defaultValue: "Couldn't send to {email}. Try again.",
+ email: input.email,
+ }),
+ notFound: t("actionErrorNotFound", {
+ defaultValue: "The resource was not found",
+ }),
+ paymentRequired: t("actionErrorPaymentRequired", {
+ defaultValue: "You need to upgrade to perform this action",
+ }),
+ };
+ toast.error(messages[data.reason]);
+ announce(messages[data.reason]);
+ if (data.reason === "sendFailed") {
+ form.setValue("email", input.email);
+ }
+ },
+ onError: (_error, input) => {
+ setSending((prev) => prev.filter((address) => address !== input.email));
form.setValue("email", input.email);
- }
- },
- onError: ({ input }) => {
- setSending((prev) => prev.filter((address) => address !== input.email));
- form.setValue("email", input.email);
- },
- });
+ },
+ }),
+ );
const onInvalid = () => {
announce(
@@ -206,7 +205,7 @@ export function InviteByEmail() {
setSending((prev) => [address, ...prev]);
form.reset();
form.setFocus("email");
- sendInvite.execute({ pollId: poll.id, email: address });
+ sendInvite.mutate({ pollId: poll.id, email: address });
};
return (
diff --git a/apps/web/src/features/poll/components/invitee-list.tsx b/apps/web/src/features/poll/components/invitee-list.tsx
index 8d534c81c..8e9e78cec 100644
--- a/apps/web/src/features/poll/components/invitee-list.tsx
+++ b/apps/web/src/features/poll/components/invitee-list.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { posthog } from "@rallly/posthog/client";
import { cn } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
@@ -10,6 +11,7 @@ import {
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import {
LinkIcon,
MailIcon,
@@ -23,7 +25,6 @@ import { usePoll } from "@/features/poll/client";
import { revokePollInviteAction } from "@/features/poll/invite/actions";
import type { PollInviteStatus } from "@/features/poll/invite/utils";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export type InviteeRowStatus = PollInviteStatus | "sending";
@@ -83,30 +84,31 @@ function InviteeRowMenu({
const [state, copyToClipboard] = useCopyToClipboard();
// The success handler refetches the list, which is what drops the row.
- const revoke = useSafeAction(revokePollInviteAction, {
- onSuccess: ({ data }) => {
- if (!data) return;
- if (data.ok) {
- toast(
- t("shareDialogInviteRemoved", {
- defaultValue: "Invite for {email} removed",
- email,
- }),
- );
- return;
- }
- toast.error(
- data.reason === "alreadyResponded"
- ? t("shareDialogAlreadyResponded", {
- defaultValue: "{email} has already responded",
+ const revoke = useMutation(
+ mutationOptions(revokePollInviteAction, {
+ onSuccess: (data) => {
+ if (data.ok) {
+ toast(
+ t("shareDialogInviteRemoved", {
+ defaultValue: "Invite for {email} removed",
email,
- })
- : t("actionErrorNotFound", {
- defaultValue: "The resource was not found",
}),
- );
- },
- });
+ );
+ return;
+ }
+ toast.error(
+ data.reason === "alreadyResponded"
+ ? t("shareDialogAlreadyResponded", {
+ defaultValue: "{email} has already responded",
+ email,
+ })
+ : t("actionErrorNotFound", {
+ defaultValue: "The resource was not found",
+ }),
+ );
+ },
+ }),
+ );
// react-use records a failed copy as `error` and a successful one as
// `value`; the toast only claims success in the second case.
@@ -163,7 +165,7 @@ function InviteeRowMenu({
<DropdownMenuItem
variant="destructive"
disabled={revoke.isPending}
- onClick={() => revoke.execute({ pollId: poll.id, inviteId })}
+ onClick={() => revoke.mutate({ pollId: poll.id, inviteId })}
>
<Trash2Icon />
<Trans i18nKey="shareDialogRemoveInvite" defaults="Remove invite" />
diff --git a/apps/web/src/features/poll/components/notification-toggle.tsx b/apps/web/src/features/poll/components/notification-toggle.tsx
index bc1249ca2..0a89405d0 100644
--- a/apps/web/src/features/poll/components/notification-toggle.tsx
+++ b/apps/web/src/features/poll/components/notification-toggle.tsx
@@ -1,53 +1,56 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import { toast } from "@rallly/ui/sonner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
+import { useMutation } from "@tanstack/react-query";
import { BellIcon, BellOffIcon } from "lucide-react";
import { setPollMutedAction } from "@/features/poll/actions";
import { usePoll } from "@/features/poll/client";
import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function NotificationToggle() {
const poll = usePoll();
const { user, ownsObject } = useUser();
const { t } = useTranslation();
- // useSafeAction refreshes the router on success, which is what flips
- // `poll.muted` in the layout's server props.
- const setPollMuted = useSafeAction(setPollMutedAction, {
- onSuccess: ({ data, input }) => {
- if (!data?.ok) {
- return;
- }
- if (input.muted) {
- toast(
- t("notificationToggleMutedToast", {
- defaultValue: "Notifications are off for this poll",
- }),
- {
- icon: <BellOffIcon className="size-4" />,
- action: {
- label: t("undo", { defaultValue: "Undo" }),
- onClick: () => {
- setPollMuted.execute({ pollId: input.pollId, muted: false });
+ // The action refreshes the page, which is what flips `poll.muted` in the
+ // layout's server props.
+ const setPollMuted = useMutation(
+ mutationOptions(setPollMutedAction, {
+ onSuccess: (data, input) => {
+ if (!data.ok) {
+ return;
+ }
+ if (input.muted) {
+ toast(
+ t("notificationToggleMutedToast", {
+ defaultValue: "Notifications are off for this poll",
+ }),
+ {
+ icon: <BellOffIcon className="size-4" />,
+ action: {
+ label: t("undo", { defaultValue: "Undo" }),
+ onClick: () => {
+ setPollMuted.mutate({ pollId: input.pollId, muted: false });
+ },
},
},
- },
- );
- } else {
- toast(
- t("notificationToggleUnmutedToast", {
- defaultValue: "Notifications are on for this poll",
- }),
- {
- icon: <BellIcon className="size-4" />,
- },
- );
- }
- },
- });
+ );
+ } else {
+ toast(
+ t("notificationToggleUnmutedToast", {
+ defaultValue: "Notifications are on for this poll",
+ }),
+ {
+ icon: <BellIcon className="size-4" />,
+ },
+ );
+ }
+ },
+ }),
+ );
if (user?.isGuest || !ownsObject(poll)) {
return null;
@@ -68,9 +71,9 @@ export function NotificationToggle() {
})
: t("muteNotifications", { defaultValue: "Mute notifications" })
}
- loading={setPollMuted.isExecuting}
+ loading={setPollMuted.isPending}
onClick={() => {
- setPollMuted.execute({ pollId: poll.id, muted: !poll.muted });
+ setPollMuted.mutate({ pollId: poll.id, muted: !poll.muted });
}}
>
{poll.muted ? <BellOffIcon /> : <BellIcon />}
diff --git a/apps/web/src/features/scheduled-event/actions.ts b/apps/web/src/features/scheduled-event/actions.ts
index 9ffeff48b..f0d9fe572 100644
--- a/apps/web/src/features/scheduled-event/actions.ts
+++ b/apps/web/src/features/scheduled-event/actions.ts
@@ -2,6 +2,7 @@
import { sendEventRsvpConfirmationEmail } from "@rallly/emails/templates/event-rsvp-confirmation";
import { createLogger } from "@rallly/logger";
+import { refresh } from "next/cache";
import { headers } from "next/headers";
import { after } from "next/server";
import * as z from "zod";
@@ -288,5 +289,11 @@ export const cancelRsvpAction = actionClient
}),
)
.action(async ({ parsedInput }) => {
- return await cancelRsvp({ inviteUid: parsedInput.inviteUid });
+ const result = await cancelRsvp({ inviteUid: parsedInput.inviteUid });
+
+ // A not_found result means the RSVP is already gone, so the page is
+ // stale either way.
+ refresh();
+
+ return result;
});
diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.ts
index a1ad95a54..e7660c9ad 100644
--- a/apps/web/src/features/space/actions.ts
+++ b/apps/web/src/features/space/actions.ts
@@ -81,9 +81,6 @@ export const setActiveSpaceAction = authActionClient
});
}
- // Renders the new space's tree into the action response, so the client
- // needs no follow-up router.refresh(). Unlike revalidatePath, this
- // leaves the Data Cache alone.
refresh();
track(ctx.user, {
@@ -128,6 +125,8 @@ export const createSpaceAction = authActionClient
},
});
+ refresh();
+
return space;
});
@@ -175,6 +174,8 @@ export const deleteSpaceAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const updateSpaceAction = authActionClient
@@ -225,6 +226,8 @@ export const updateSpaceAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const updateSpaceShowBrandingAction = authActionClient
@@ -272,6 +275,8 @@ export const updateSpaceShowBrandingAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const updateSpaceHideAttributionAction = authActionClient
@@ -319,6 +324,8 @@ export const updateSpaceHideAttributionAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const updateSpaceSharedAction = authActionClient
@@ -365,6 +372,8 @@ export const updateSpaceSharedAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const getSpaceImageUploadUrlAction = authActionClient
@@ -396,6 +405,8 @@ export const updateSpaceImageAction = authActionClient
spaceId: space.id,
imageKey: parsedInput.imageKey,
});
+
+ refresh();
});
export const removeSpaceImageAction = authActionClient
@@ -403,4 +414,6 @@ export const removeSpaceImageAction = authActionClient
.use(spaceUpdateAbilityMiddleware)
.action(async ({ ctx }) => {
await updateSpaceImage({ spaceId: ctx.space.id, imageKey: null });
+
+ refresh();
});
diff --git a/apps/web/src/features/space/client.tsx b/apps/web/src/features/space/client.tsx
index 6c2e6eabd..221806a7a 100644
--- a/apps/web/src/features/space/client.tsx
+++ b/apps/web/src/features/space/client.tsx
@@ -1,6 +1,8 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import React from "react";
import type { PayWallTrigger } from "@/features/billing/client";
import { showPayWall, useIsFree } from "@/features/billing/client";
@@ -11,7 +13,6 @@ import type { SpaceDTO } from "@/features/space/types";
import { isSpaceBrandingActive } from "@/features/space/utils";
import { useAuthedUser } from "@/features/user/client";
import { useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { defineAbilityForSpace } from "./ability";
import { updateSpaceHideAttributionAction } from "./actions";
@@ -93,7 +94,9 @@ export function useHideAttributionToggle({
}) {
const isFree = useIsFree();
const { t } = useTranslation();
- const updateHideAttribution = useSafeAction(updateSpaceHideAttributionAction);
+ const updateHideAttribution = useMutation(
+ mutationOptions(updateSpaceHideAttributionAction),
+ );
// Optimistic value shown until the post-action router refresh delivers
// the updated space data; reverts automatically if the action fails.
@@ -108,19 +111,20 @@ export function useHideAttributionToggle({
React.startTransition(async () => {
setOptimisticValue(newChecked);
- const result = await updateHideAttribution.executeAsync({
- hideAttribution: newChecked,
- });
-
- if (!result?.serverError && !result?.validationErrors) {
+ try {
+ await updateHideAttribution.mutateAsync({
+ hideAttribution: newChecked,
+ });
toast.success(t("saved", { defaultValue: "Saved" }));
+ } catch {
+ // The mutation cache toasts the error
}
});
};
return {
hideAttribution: optimisticValue,
- isExecuting: updateHideAttribution.isExecuting,
+ isPending: updateHideAttribution.isPending,
toggle,
};
}
diff --git a/apps/web/src/features/space/components/create-space-dialog.tsx b/apps/web/src/features/space/components/create-space-dialog.tsx
index e5dde2b56..14db3e256 100644
--- a/apps/web/src/features/space/components/create-space-dialog.tsx
+++ b/apps/web/src/features/space/components/create-space-dialog.tsx
@@ -1,5 +1,7 @@
"use client";
+
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
@@ -20,11 +22,11 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { createSpaceAction } from "@/features/space/actions";
import { createSpaceSchema } from "@/features/space/schema";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
export function CreateSpaceDialog(props: DialogProps) {
const form = useForm({
@@ -34,7 +36,7 @@ export function CreateSpaceDialog(props: DialogProps) {
},
});
- const createSpace = useSafeAction(createSpaceAction);
+ const createSpace = useMutation(mutationOptions(createSpaceAction));
return (
<Dialog {...props}>
@@ -53,11 +55,14 @@ export function CreateSpaceDialog(props: DialogProps) {
</DialogHeader>
<form
onSubmit={form.handleSubmit(async ({ name }) => {
- const result = await createSpace.executeAsync({ name });
- if (result?.data) {
- props.onOpenChange?.(false);
- form.reset();
+ try {
+ await createSpace.mutateAsync({ name });
+ } catch {
+ // The mutation cache toasts the error
+ return;
}
+ props.onOpenChange?.(false);
+ form.reset();
})}
>
<FormField
diff --git a/apps/web/src/features/space/components/remove-attribution-popover.tsx b/apps/web/src/features/space/components/remove-attribution-popover.tsx
index c880bcd0b..2e9e0838c 100644
--- a/apps/web/src/features/space/components/remove-attribution-popover.tsx
+++ b/apps/web/src/features/space/components/remove-attribution-popover.tsx
@@ -22,7 +22,7 @@ export function RemoveAttributionPopover({ pollId }: { pollId: string }) {
const { t } = useTranslation();
// Dismissed before opening the pay wall so the dialog doesn't stack on it
const popover = useDialog();
- const { isExecuting, toggle } = useHideAttributionToggle({
+ const { isPending, toggle } = useHideAttributionToggle({
// The badge is only rendered while attribution is shown
hideAttribution: false,
payWallTrigger: {
@@ -84,7 +84,7 @@ export function RemoveAttributionPopover({ pollId }: { pollId: string }) {
<Button
variant="primary"
className="w-full"
- disabled={isExecuting}
+ disabled={isPending}
onClick={() => toggle(true)}
>
<Trans i18nKey="remove" defaults="Remove" />
diff --git a/apps/web/src/features/space/components/space-dropdown.tsx b/apps/web/src/features/space/components/space-dropdown.tsx
index 926c40a19..ec33f1bb8 100644
--- a/apps/web/src/features/space/components/space-dropdown.tsx
+++ b/apps/web/src/features/space/components/space-dropdown.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { cn } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import { useDialog } from "@rallly/ui/dialog";
@@ -13,6 +14,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
+import { useMutation } from "@tanstack/react-query";
import {
ChevronsUpDownIcon,
PlusIcon,
@@ -28,7 +30,6 @@ import { SpaceRole } from "@/features/space/components/space-role";
import { SpaceTierLabel } from "@/features/space/components/space-tier";
import type { MemberRole, SpaceTier } from "@/features/space/schema";
import { Trans } from "@/i18n/client";
-import { useRevalidatingSafeAction } from "@/lib/safe-action/client";
import { CreateSpaceDialog } from "./create-space-dialog";
import { SpaceIcon } from "./space-icon";
@@ -46,9 +47,11 @@ export function SpaceDropdown({
const { data: activeSpace } = useSpace();
const [pendingSpaceId, setPendingSpaceId] = React.useState<string>();
- const setActiveSpace = useRevalidatingSafeAction(setActiveSpaceAction, {
- onError: () => setPendingSpaceId(undefined),
- });
+ const setActiveSpace = useMutation(
+ mutationOptions(setActiveSpaceAction, {
+ onError: () => setPendingSpaceId(undefined),
+ }),
+ );
const newSpaceDialog = useDialog();
const pendingSpace = spaces.find((space) => space.id === pendingSpaceId);
@@ -95,7 +98,7 @@ export function SpaceDropdown({
onValueChange={(value) => {
if (value === selectedSpaceId) return;
setPendingSpaceId(value);
- setActiveSpace.execute({ spaceId: value });
+ setActiveSpace.mutate({ spaceId: value });
}}
>
{spaces.map((space) => (
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index 676361d9d..9ed0076da 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -1,7 +1,9 @@
"use server";
+
import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import { supportedLngs } from "@rallly/languages";
+import { refresh } from "next/cache";
import { headers } from "next/headers";
import * as z from "zod";
import { avatarAssetProfile } from "@/features/user/constants";
@@ -41,6 +43,8 @@ export const updateUserNameAction = authActionClient
body: { name: parsedInput.name },
headers: await headers(),
});
+
+ refresh();
});
export const updateLocalizationAction = authActionClient
@@ -69,6 +73,8 @@ export const updateLocalizationAction = authActionClient
},
headers: await headers(),
});
+
+ refresh();
});
// Better-Auth's request-email-change endpoint returns success without sending
@@ -142,6 +148,8 @@ export const updateUserAvatarAction = authActionClient
});
},
});
+
+ refresh();
});
export const removeUserAvatarAction = authActionClient
@@ -157,6 +165,8 @@ export const removeUserAvatarAction = authActionClient
});
},
});
+
+ refresh();
});
export const changeRoleAction = adminActionClient
@@ -196,6 +206,8 @@ export const changeRoleAction = adminActionClient
}
await updateUserRole({ userId: targetUser.id, role });
+
+ refresh();
});
export const unbanUserAction = adminActionClient
@@ -234,4 +246,6 @@ export const unbanUserAction = adminActionClient
}
await unbanUser({ userId });
+
+ refresh();
});
diff --git a/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx b/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx
index 2b904ab10..6b6de6ad4 100644
--- a/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx
+++ b/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx
@@ -12,10 +12,11 @@ vi.mock("@/lib/utils/date-time-utils", () => ({
getBrowserTimeZone: () => mockTimeZone,
}));
-const { mockExecute } = vi.hoisted(() => ({ mockExecute: vi.fn() }));
+const { mockMutate } = vi.hoisted(() => ({ mockMutate: vi.fn() }));
vi.mock("@/features/user/actions", () => ({ updateLocalizationAction: {} }));
-vi.mock("@/lib/safe-action/client", () => ({
- useSafeAction: () => ({ execute: mockExecute }),
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useMutation: () => ({ mutate: mockMutate }),
}));
function renderDialog(props: { homeTimeZone?: string } = {}) {
@@ -29,7 +30,7 @@ function renderDialog(props: { homeTimeZone?: string } = {}) {
describe("TimeZoneMismatchDialog", () => {
beforeEach(() => {
mockTimeZone = "America/New_York";
- mockExecute.mockClear();
+ mockMutate.mockClear();
});
afterEach(() => {
@@ -83,7 +84,7 @@ describe("TimeZoneMismatchDialog", () => {
await user.click(screen.getByText("Yes, update my time zone"));
- expect(mockExecute).toHaveBeenCalledWith({ timeZone: "America/New_York" });
+ expect(mockMutate).toHaveBeenCalledWith({ timeZone: "America/New_York" });
});
it("shows when the zone changes while the tab is open and regains focus", async () => {
@@ -112,7 +113,7 @@ describe("TimeZoneMismatchDialog", () => {
await user.click(screen.getByText("No, keep the current time zone"));
- expect(mockExecute).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
expect(
screen.queryByText("Time zone mismatch detected"),
).not.toBeInTheDocument();
diff --git a/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx b/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx
index 8f847658c..3c0a23044 100644
--- a/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx
+++ b/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -8,11 +9,11 @@ import {
DialogHeader,
DialogTitle,
} from "@rallly/ui/dialog";
+import { useMutation } from "@tanstack/react-query";
import React from "react";
import { updateLocalizationAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";
import { useTimeZoneChange } from "@/lib/datetime/timezone-sync";
-import { useSafeAction } from "@/lib/safe-action/client";
/**
* Offers to update the account's home time zone when TimeZoneSync detects
@@ -30,7 +31,9 @@ export function TimeZoneMismatchDialog({
const [prompt, setPrompt] = React.useState<{ currentTimeZone: string }>();
- const updateLocalization = useSafeAction(updateLocalizationAction);
+ const updateLocalization = useMutation(
+ mutationOptions(updateLocalizationAction),
+ );
React.useEffect(() => {
if (change && homeTimeZone && change.currentTimeZone !== homeTimeZone) {
@@ -73,7 +76,7 @@ export function TimeZoneMismatchDialog({
<Button
variant="primary"
onClick={() => {
- updateLocalization.execute({
+ updateLocalization.mutate({
timeZone: prompt.currentTimeZone,
});
setPrompt(undefined);
diff --git a/apps/web/src/features/webhook/actions.ts b/apps/web/src/features/webhook/actions.ts
index b88fe70fc..4b40dd805 100644
--- a/apps/web/src/features/webhook/actions.ts
+++ b/apps/web/src/features/webhook/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { refresh } from "next/cache";
+
import { getActiveSpaceForUser } from "@/features/space/data";
import { loadOptionalUser } from "@/features/user/loaders";
import { AppError } from "@/lib/errors/app-error";
@@ -74,6 +76,8 @@ export const createWebhookAction = authActionClient
});
}
+ refresh();
+
return result;
});
@@ -97,6 +101,8 @@ export const setWebhookEnabledAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
export const deleteWebhookAction = authActionClient
@@ -116,6 +122,8 @@ export const deleteWebhookAction = authActionClient
space: space.id,
},
});
+
+ refresh();
});
// Each call is an outbound request to a URL the owner chose, so it is
@@ -141,5 +149,7 @@ export const sendWebhookTestEventAction = authActionClient
},
});
+ refresh();
+
return result;
});
diff --git a/apps/web/src/features/webhook/components/create-webhook-button.tsx b/apps/web/src/features/webhook/components/create-webhook-button.tsx
index dcb97a5ca..8225da0ac 100644
--- a/apps/web/src/features/webhook/components/create-webhook-button.tsx
+++ b/apps/web/src/features/webhook/components/create-webhook-button.tsx
@@ -1,6 +1,7 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Alert, AlertDescription } from "@rallly/ui/alert";
import { Button } from "@rallly/ui/button";
@@ -24,12 +25,12 @@ import {
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useMutation } from "@tanstack/react-query";
import { AlertTriangleIcon, CheckIcon, CopyIcon, PlusIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
import { useCopyToClipboard } from "react-use";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { createWebhookAction } from "../actions";
import { createWebhookInputSchema } from "../schema";
import { WebhookEventCombobox } from "./webhook-event-combobox";
@@ -38,7 +39,7 @@ export function CreateWebhookButton() {
const { t } = useTranslation();
const dialog = useDialog();
const [createdSecret, setCreatedSecret] = React.useState<string | null>(null);
- const createWebhook = useSafeAction(createWebhookAction);
+ const createWebhook = useMutation(mutationOptions(createWebhookAction));
const [, copy] = useCopyToClipboard();
const [didCopy, setDidCopy] = React.useState(false);
@@ -142,20 +143,22 @@ export function CreateWebhookButton() {
</DialogHeader>
<Form {...form}>
<form
- onSubmit={form.handleSubmit(async (data) => {
- const result = await createWebhook.executeAsync(data);
- if (result?.data?.ok) {
- setCreatedSecret(result.data.secret);
- form.reset();
- } else if (
- result?.data?.reason === "max_webhooks_exceeded"
- ) {
- toast.error(
- t("webhookLimitReached", {
- defaultValue:
- "You've reached the maximum number of webhooks. Delete one before adding another.",
- }),
- );
+ onSubmit={form.handleSubmit(async (values) => {
+ try {
+ const data = await createWebhook.mutateAsync(values);
+ if (data.ok) {
+ setCreatedSecret(data.secret);
+ form.reset();
+ } else if (data.reason === "max_webhooks_exceeded") {
+ toast.error(
+ t("webhookLimitReached", {
+ defaultValue:
+ "You've reached the maximum number of webhooks. Delete one before adding another.",
+ }),
+ );
+ }
+ } catch {
+ // The mutation cache toasts the error
}
})}
>
@@ -209,8 +212,8 @@ export function CreateWebhookButton() {
<Button
variant="primary"
type="submit"
- disabled={createWebhook.isExecuting}
- loading={createWebhook.isExecuting}
+ disabled={createWebhook.isPending}
+ loading={createWebhook.isPending}
>
<Trans i18nKey="addWebhook" defaults="Add webhook" />
</Button>
diff --git a/apps/web/src/features/webhook/components/webhook-actions.tsx b/apps/web/src/features/webhook/components/webhook-actions.tsx
index c571bd9ea..ab73c2efb 100644
--- a/apps/web/src/features/webhook/components/webhook-actions.tsx
+++ b/apps/web/src/features/webhook/components/webhook-actions.tsx
@@ -1,5 +1,6 @@
"use client";
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -19,9 +20,9 @@ import {
} from "@rallly/ui/dropdown-menu";
import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
+import { useMutation } from "@tanstack/react-query";
import { MoreVerticalIcon, SendIcon, Trash2Icon } from "lucide-react";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import {
deleteWebhookAction,
sendWebhookTestEventAction,
@@ -40,60 +41,61 @@ export function WebhookActions({
const { t } = useTranslation();
const deleteDialog = useDialog();
- const setEnabled = useSafeAction(setWebhookEnabledAction);
- const sendTestEvent = useSafeAction(sendWebhookTestEventAction, {
- onExecute: () => {
- toast.loading(
- t("webhookTestEventSending", { defaultValue: "Sending test event" }),
- { id: `webhook-test-${webhookId}` },
- );
- },
- onSuccess: ({ data }) => {
- if (!data) {
- return;
- }
- const id = `webhook-test-${webhookId}`;
- if (data.ok) {
- toast.success(
- t("webhookTestEventDelivered", {
- defaultValue: "Test event delivered",
- }),
- {
- id,
- description: t("webhookTestEventRespondedWith", {
- defaultValue: "Endpoint responded {status}",
- status: data.status,
- }),
- },
- );
- } else {
- toast.error(
- t("webhookTestEventFailed", { defaultValue: "Test event failed" }),
- { id, description: data.error },
+ const setEnabled = useMutation(mutationOptions(setWebhookEnabledAction));
+ const sendTestEvent = useMutation(
+ mutationOptions(sendWebhookTestEventAction, {
+ onMutate: () => {
+ toast.loading(
+ t("webhookTestEventSending", { defaultValue: "Sending test event" }),
+ { id: `webhook-test-${webhookId}` },
);
- }
- },
- onError: () => {
- toast.dismiss(`webhook-test-${webhookId}`);
- },
- });
- const deleteWebhook = useSafeAction(deleteWebhookAction, {
- onSuccess: () => {
- toast.success(t("webhookDeleted", { defaultValue: "Webhook deleted" }));
- },
- onSettled: () => {
- deleteDialog.dismiss();
- },
- });
+ },
+ onSuccess: (data) => {
+ const id = `webhook-test-${webhookId}`;
+ if (data.ok) {
+ toast.success(
+ t("webhookTestEventDelivered", {
+ defaultValue: "Test event delivered",
+ }),
+ {
+ id,
+ description: t("webhookTestEventRespondedWith", {
+ defaultValue: "Endpoint responded {status}",
+ status: data.status,
+ }),
+ },
+ );
+ } else {
+ toast.error(
+ t("webhookTestEventFailed", { defaultValue: "Test event failed" }),
+ { id, description: data.error },
+ );
+ }
+ },
+ onError: () => {
+ toast.dismiss(`webhook-test-${webhookId}`);
+ },
+ }),
+ );
+ const deleteWebhook = useMutation(
+ mutationOptions(deleteWebhookAction, {
+ onSuccess: () => {
+ toast.success(t("webhookDeleted", { defaultValue: "Webhook deleted" }));
+ },
+ onSettled: () => {
+ deleteDialog.dismiss();
+ },
+ }),
+ );
return (
<>
<Switch
checked={enabled}
- disabled={setEnabled.isExecuting}
+ disabled={setEnabled.isPending}
aria-label={t("enabled", { defaultValue: "Enabled" })}
onCheckedChange={(checked) => {
- setEnabled.execute({ webhookId, enabled: checked });
+ setEnabled.mutate({ webhookId, enabled: checked });
}}
/>
<DropdownMenu>
@@ -110,9 +112,9 @@ export function WebhookActions({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
- disabled={sendTestEvent.isExecuting}
+ disabled={sendTestEvent.isPending}
onClick={() => {
- sendTestEvent.execute({ webhookId });
+ sendTestEvent.mutate({ webhookId });
}}
>
<SendIcon />
@@ -146,9 +148,9 @@ export function WebhookActions({
<DialogFooter>
<Button
variant="destructive"
- loading={deleteWebhook.isExecuting}
+ loading={deleteWebhook.isPending}
onClick={() => {
- deleteWebhook.execute({ webhookId });
+ deleteWebhook.mutate({ webhookId });
}}
>
<Trans i18nKey="delete" defaults="Delete" />
diff --git a/apps/web/src/lib/safe-action/client.ts b/apps/web/src/lib/safe-action/client.ts
deleted file mode 100644
index 7e99f3be8..000000000
--- a/apps/web/src/lib/safe-action/client.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-"use client";
-import { toast } from "@rallly/ui/sonner";
-import { useQueryClient } from "@tanstack/react-query";
-import { useRouter } from "next/navigation";
-import { useAction } from "next-safe-action/hooks";
-import { useTranslation } from "@/i18n/client";
-import type { AppErrorCode } from "@/lib/errors/app-error";
-
-export const useSafeAction: typeof useAction = (action, options) => {
- const router = useRouter();
- return useSafeActionBase(action, {
- ...options,
- onSuccess: (args) => {
- router.refresh();
- options?.onSuccess?.(args);
- },
- });
-};
-
-/**
- * For actions that call refresh() or revalidatePath: the action response
- * already carries the re-rendered page, so a router.refresh() would be a
- * second render.
- */
-export const useRevalidatingSafeAction: typeof useAction = (action, options) =>
- useSafeActionBase(action, options);
-
-const useSafeActionBase: typeof useAction = (action, options) => {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- return useAction(action, {
- ...options,
- onSuccess: (args) => {
- // Same blanket invalidation the tRPC mutation override does, so a
- // client query never shows stale data after a write.
- void queryClient.invalidateQueries();
- options?.onSuccess?.(args);
- },
- onError: (args) => {
- const { error } = args;
- if (error.serverError) {
- let translatedDescription = "An unexpected error occurred";
-
- switch (error.serverError as AppErrorCode) {
- case "UNAUTHORIZED":
- translatedDescription = t("actionErrorUnauthorized", {
- defaultValue: "You are not authorized to perform this action",
- });
- break;
- case "NOT_FOUND":
- translatedDescription = t("actionErrorNotFound", {
- defaultValue: "The resource was not found",
- });
- break;
- case "FORBIDDEN":
- translatedDescription = t("actionErrorForbidden", {
- defaultValue: "You are not allowed to perform this action",
- });
- break;
- case "INTERNAL_SERVER_ERROR":
- translatedDescription = t("actionErrorInternalServerError", {
- defaultValue: "An internal server error occurred",
- });
- break;
- case "TOO_MANY_REQUESTS":
- translatedDescription = t("actionErrorTooManyRequests", {
- defaultValue: "You are making too many requests",
- });
- break;
- case "PAYMENT_REQUIRED":
- translatedDescription = t("actionErrorPaymentRequired", {
- defaultValue: "You need to upgrade to perform this action",
- });
- break;
- case "SERVICE_UNAVAILABLE":
- translatedDescription = t("actionErrorServiceUnavailable", {
- defaultValue:
- "The service required to perform this action is not available",
- });
- break;
- case "PAYLOAD_TOO_LARGE":
- translatedDescription = t("actionErrorPayloadTooLarge", {
- defaultValue:
- "The file you uploaded is too large. Please try a smaller file.",
- });
- break;
- }
-
- toast.error(translatedDescription);
- }
- options?.onError?.(args);
- },
- });
-};
diff --git a/apps/web/src/trpc/client.ts b/apps/web/src/trpc/client.ts
index 9855fe05c..5a54fd510 100644
--- a/apps/web/src/trpc/client.ts
+++ b/apps/web/src/trpc/client.ts
@@ -2,13 +2,4 @@ import { createTRPCReact } from "@trpc/react-query";
import type { AppRouter } from "@/trpc/routers";
-export const trpc = createTRPCReact<AppRouter>({
- overrides: {
- useMutation: {
- async onSuccess(opts) {
- await opts.originalFn();
- await opts.queryClient.invalidateQueries();
- },
- },
- },
-});
+export const trpc = createTRPCReact<AppRouter>();
diff --git a/apps/web/src/trpc/client/provider.tsx b/apps/web/src/trpc/client/provider.tsx
index 43bf7eba0..ab939b429 100644
--- a/apps/web/src/trpc/client/provider.tsx
+++ b/apps/web/src/trpc/client/provider.tsx
@@ -1,4 +1,5 @@
"use client";
+import { isActionMutationError } from "@next-safe-action/adapter-tanstack-query";
import { toast } from "@rallly/ui/sonner";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import {
@@ -8,10 +9,12 @@ import {
QueryClientProvider,
} from "@tanstack/react-query";
import { httpBatchLink, TRPCClientError } from "@trpc/client";
+import { isNavigationError } from "next-safe-action";
import React from "react";
import superjson from "superjson";
import { useTranslation } from "@/i18n/client";
import { signOut } from "@/lib/auth-client";
+import type { AppErrorCode } from "@/lib/errors/app-error";
import { registerBrowserQueryClient } from "@/lib/query-client";
import { trpc } from "../client";
import type { AppRouter } from "../routers";
@@ -32,60 +35,48 @@ function isAbortError(error: TRPCClientError<AppRouter>) {
export function TRPCProvider(props: { children: React.ReactNode }) {
const { t } = useTranslation();
const [queryClient] = React.useState(() => {
- function handleError(error: Error) {
- if (!isTRPCClientError(error)) {
- return;
- }
-
- // A cancelled request is not a failure — never warn about connectivity
- if (isAbortError(error)) {
- return;
- }
-
- // Missing error data means no usable server response: the request
- // failed in transit or the response was not a tRPC error envelope
- // (e.g. an HTML error page from a proxy)
- if (!error.data) {
- toast.error(
- t("actionErrorNetwork", {
- defaultValue:
- "Unable to reach the server. Please check your connection and try again.",
- }),
- { id: "network-error" },
- );
- return;
- }
+ function showNetworkErrorToast() {
+ toast.error(
+ t("actionErrorNetwork", {
+ defaultValue:
+ "Unable to reach the server. Please check your connection and try again.",
+ }),
+ { id: "network-error" },
+ );
+ }
- switch (error.data?.code) {
- case "UNAUTHORIZED":
+ // One table for both transports: tRPC error codes and the codes
+ // handleServerError returns for server actions share their names.
+ function showErrorToast(code: string | undefined) {
+ switch (code as AppErrorCode | undefined) {
+ case "INVALID_SESSION":
// Never sign out automatically — a failed sign out turns this
// into an infinite loop with the login page.
- if (error.data.appError === "INVALID_SESSION") {
- toast.error(
- t("actionErrorInvalidSession", {
- defaultValue: "Your session is no longer valid",
- }),
- {
- id: "invalid-session",
- duration: Number.POSITIVE_INFINITY,
- action: {
- label: t("signOut", { defaultValue: "Sign out" }),
- onClick: () => {
- signOut().finally(() => {
- window.location.href = "/login";
- });
- },
+ toast.error(
+ t("actionErrorInvalidSession", {
+ defaultValue: "Your session is no longer valid",
+ }),
+ {
+ id: "invalid-session",
+ duration: Number.POSITIVE_INFINITY,
+ action: {
+ label: t("signOut", { defaultValue: "Sign out" }),
+ onClick: () => {
+ signOut().finally(() => {
+ window.location.href = "/login";
+ });
},
},
- );
- } else {
- toast.error(
- t("actionErrorUnauthorized", {
- defaultValue: "You are not authorized to perform this action",
- }),
- { id: "unauthorized" },
- );
- }
+ },
+ );
+ break;
+ case "UNAUTHORIZED":
+ toast.error(
+ t("actionErrorUnauthorized", {
+ defaultValue: "You are not authorized to perform this action",
+ }),
+ { id: "unauthorized" },
+ );
break;
case "FORBIDDEN":
toast.error(
@@ -141,6 +132,57 @@ export function TRPCProvider(props: { children: React.ReactNode }) {
}
}
+ function handleTRPCError(error: TRPCClientError<AppRouter>) {
+ // A cancelled request is not a failure — never warn about connectivity
+ if (isAbortError(error)) {
+ return;
+ }
+
+ // Missing error data means no usable server response: the request
+ // failed in transit or the response was not a tRPC error envelope
+ // (e.g. an HTML error page from a proxy)
+ if (!error.data) {
+ showNetworkErrorToast();
+ return;
+ }
+
+ showErrorToast(
+ error.data.appError === "INVALID_SESSION"
+ ? "INVALID_SESSION"
+ : error.data.code,
+ );
+ }
+
+ function handleQueryError(error: Error) {
+ if (isTRPCClientError(error)) {
+ handleTRPCError(error);
+ }
+ }
+
+ function handleMutationError(error: Error) {
+ if (isTRPCClientError(error)) {
+ handleTRPCError(error);
+ return;
+ }
+
+ if (isActionMutationError(error)) {
+ // Validation errors belong to the form that sent the input
+ if (typeof error.serverError === "string") {
+ showErrorToast(error.serverError);
+ }
+ return;
+ }
+
+ // Redirects and notFound() are rethrown for Next.js to handle
+ if (isNavigationError(error)) {
+ return;
+ }
+
+ // A server action that throws instead of returning a result never
+ // got a usable response: the request failed in transit
+ showNetworkErrorToast();
+ }
+
const client = new QueryClient({
defaultOptions: {
queries: {
@@ -148,8 +190,15 @@ export function TRPCProvider(props: { children: React.ReactNode }) {
staleTime: 1000 * 60,
},
},
- queryCache: new QueryCache({ onError: handleError }),
- mutationCache: new MutationCache({ onError: handleError }),
+ queryCache: new QueryCache({ onError: handleQueryError }),
+ mutationCache: new MutationCache({
+ onError: handleMutationError,
+ onSuccess: () => {
+ // Blanket invalidation after every write, so a client query never
+ // shows stale data
+ void client.invalidateQueries();
+ },
+ }),
});
// Sign-out refreshes the router but keeps this provider mounted, so
// signOut() clears the cache through this registration.
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3db6a7cfb..401392ef2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -97,7 +97,7 @@ importers:
version: 8.1.0([email protected])
'@vercel/analytics':
specifier: ^1.5.0
dayjs:
specifier: ^1.11.13
version: 1.11.19
@@ -139,7 +139,7 @@ importers:
version: 6.0.0(@types/[email protected])([email protected])
next-seo:
specifier: ^6.1.0
pg:
specifier: ^8.17.1
version: 8.18.0
@@ -225,6 +225,9 @@ importers:
'@marsidev/react-turnstile':
specifier: ^1.5.3
+ '@next-safe-action/adapter-tanstack-query':
+ specifier: 0.1.2
'@next/env':
specifier: 16.3.3
version: 16.3.3
@@ -624,7 +627,7 @@ importers:
version: link:../tsconfig
'@react-email/ui':
specifier: ^6.9.3
'@types/react':
specifier: 19.2.13
version: 19.2.13
@@ -3387,6 +3390,15 @@ packages:
cpu: [x64]
os: [linux]
+ '@next-safe-action/[email protected]':
+ resolution: {integrity: sha512-OD/3H1JQ+dd1BRj10xoreJyqDRpMm1x6Z+Ty0663ImMWwZ8yG7uTxR9wtxM2yr0nQ/XOsex/W2ZNUebCxoIyyg==}
+ engines: {node: '>=18.17'}
+ peerDependencies:
+ '@tanstack/react-query': '>= 5.0.0'
+ next: 16.3.3
+ next-safe-action: '>=8.1.10'
+ react: '>= 18.2.0'
+
resolution: {integrity: sha512-pJFJrjUnxac2RBEgRIhXqoRkaSxMGQEGvvLhPKA2h1hXAzq60DzRj8Vp8+um2cMuHRuLcwRFYNlcuS74/hZ7AQ==}
@@ -15907,6 +15919,13 @@ snapshots:
'@napi-rs/[email protected]':
optional: true
+ dependencies:
+ '@tanstack/react-query': 5.90.20([email protected])
+ react: 19.2.6
+
dependencies:
webpack-bundle-analyzer: 4.10.1
@@ -17499,10 +17518,10 @@ snapshots:
dependencies:
react: 19.2.6
dependencies:
esbuild: 0.28.1
transitivePeerDependencies:
- '@babel/core'
- '@opentelemetry/api'
@@ -19809,9 +19828,9 @@ snapshots:
dependencies:
uncrypto: 0.1.3
optionalDependencies:
react: 19.2.6
@@ -23908,9 +23927,9 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6([email protected])
dependencies:
react: 19.2.6
react-dom: 19.2.6([email protected])
@@ -23946,7 +23965,34 @@ snapshots:
- '@types/node'
- babel-plugin-macros
+ dependencies:
+ '@next/env': 16.3.3
+ '@swc/helpers': 0.5.23
+ baseline-browser-mapping: 2.11.19
+ caniuse-lite: 1.0.30001810
+ postcss: 8.5.23
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+ styled-jsx: 5.1.6(@babel/[email protected])([email protected])
+ optionalDependencies:
+ '@next/swc-darwin-arm64': 16.3.3
+ '@next/swc-darwin-x64': 16.3.3
+ '@next/swc-linux-arm64-gnu': 16.3.3
+ '@next/swc-linux-arm64-musl': 16.3.3
+ '@next/swc-linux-x64-gnu': 16.3.3
+ '@next/swc-linux-x64-musl': 16.3.3
+ '@next/swc-win32-arm64-msvc': 16.3.3
+ '@next/swc-win32-x64-msvc': 16.3.3
+ '@opentelemetry/api': 1.9.0
+ '@playwright/test': 1.58.1
+ sharp: 0.35.3(@types/[email protected])
+ transitivePeerDependencies:
+ - '@babel/core'
+ - '@types/node'
+ - babel-plugin-macros
+
dependencies:
'@next/env': 16.3.3
'@swc/helpers': 0.5.23