From 4e02b22472edca1a74085829563412efcab7d07e Mon Sep 17 00:00:00 2001 From: Nafees Nazik <84864519+G3root@users.noreply.github.com> Date: Thu, 8 Dec 2022 02:25:41 +0530 Subject: [PATCH] fix: add optimistic update for disabling forms (#5547) --- .../routing-forms/components/FormActions.tsx | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/app-store/ee/routing-forms/components/FormActions.tsx b/packages/app-store/ee/routing-forms/components/FormActions.tsx index ca0865f9a2..781e0341df 100644 --- a/packages/app-store/ee/routing-forms/components/FormActions.tsx +++ b/packages/app-store/ee/routing-forms/components/FormActions.tsx @@ -234,14 +234,31 @@ const actionsCtx = createContext({ export function FormActionsProvider({ appUrl, children }: { appUrl: string; children: React.ReactNode }) { const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogFormId, setDeleteDialogFormId] = useState(null); - const router = useRouter(); + const utils = trpc.useContext(); const toggleMutation = trpc.viewer.appRoutingForms.formMutation.useMutation({ - onError: () => { - showToast(`Something went wrong`, "error"); + onMutate: async ({ id: formId, disabled }) => { + await utils.viewer.appRoutingForms.forms.cancel(); + const previousValue = utils.viewer.appRoutingForms.forms.getData(); + if (previousValue) { + const itemIndex = previousValue.findIndex(({ id }) => id === formId); + const prevValueTemp = [...previousValue]; + + if (itemIndex !== -1 && prevValueTemp[itemIndex] && disabled !== undefined) { + prevValueTemp[itemIndex].disabled = disabled; + } + utils.viewer.appRoutingForms.forms.setData(undefined, prevValueTemp); + } + return { previousValue }; }, - onSuccess: () => { - router.replace(router.asPath); + onSettled: () => { + utils.viewer.appRoutingForms.forms.invalidate(); + }, + onError: (err, value, context) => { + if (context?.previousValue) { + utils.viewer.appRoutingForms.forms.setData(undefined, context.previousValue); + } + showToast("Something went wrong", "error"); }, });