The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-3138: Make inline update rollback deterministic (#82418)
Stas Gavrylov34c44f0f7fc7
diff --git a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.tsindex 3f154b09fcd..4ab1ac7375a 100644--- a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts@@ -1081,7 +1081,7 @@ LIMIT}).as("updateTransformError");cy.log("Toggle incremental on");- getIncrementalSwitch().click();+ getIncrementalSwitch().findByRole("switch").should("be.enabled").click();cy.log("Wait for the failed request");cy.wait("@updateTransformError");diff --git a/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.tsx b/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.tsxindex 5814864a204..55158f01e80 100644--- a/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.tsx+++ b/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.tsx@@ -1,6 +1,6 @@import { useDebouncedCallback } from "@mantine/hooks";import { useFormikContext } from "formik";-import { useCallback, useRef } from "react";+import { useCallback, useEffect, useRef } from "react";import _ from "underscore";import { FormObserver } from "metabase/forms";@@ -19,7 +19,8 @@ const DEFAULT_INLINE_UPDATE_DEBOUNCE_MS = 300;* Calls the update function when form values change.* Processes updates sequentially to avoid race conditions.*- * Note: To enable automatic form rollback on error, use `enableReinitialize` on FormProvider.+ * Failed updates roll back to the latest successfully updated values.+ * Use `enableReinitialize` when the form should also adopt changing external `initialValues`.** @param update - Async function called with new form values* @param onSuccess - Optional callback called with the update result on success@@ -44,9 +45,16 @@ export const FormInlineUpdater = <T, TSuccess>({debounceMs = DEFAULT_INLINE_UPDATE_DEBOUNCE_MS,onBeforeUpdate,}: FormInlineUpdaterProps<T, TSuccess>) => {- const { initialValues } = useFormikContext<T>();+ const { initialValues, resetForm } = useFormikContext<T>();const updateInProgress = useRef(false);const pendingUpdate = useRef<T | null>(null);+ const lastSuccessfulValues = useRef(initialValues);++ useEffect(() => {+ if (!updateInProgress.current) {+ lastSuccessfulValues.current = initialValues;+ }+ }, [initialValues]);const processUpdate = useCallback(async (values: T) => {@@ -60,10 +68,12 @@ export const FormInlineUpdater = <T, TSuccess>({try {const result = await update(values);+ lastSuccessfulValues.current = values;onSuccess?.(result);} catch (err) {- // On error, discard any pending updates+ // On error, discard any pending updates and restore the last saved valuespendingUpdate.current = null;+ resetForm({ values: lastSuccessfulValues.current });onError?.(err);updateInProgress.current = false;return;@@ -78,7 +88,7 @@ export const FormInlineUpdater = <T, TSuccess>({await processUpdate(nextValues);}},- [update, onSuccess, onError],+ [update, onSuccess, onError, resetForm],);const handleChange = useDebouncedCallback(async (values: T) => {diff --git a/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.unit.spec.tsx b/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.unit.spec.tsxnew file mode 100644index 00000000000..65964191bb6--- /dev/null+++ b/frontend/src/metabase/forms/components/FormInlineUpdater/FormInlineUpdater.unit.spec.tsx@@ -0,0 +1,123 @@+import userEvent from "@testing-library/user-event";++import { render, screen, waitFor } from "__support__/ui";+import { Form, FormProvider, FormSwitch } from "metabase/forms";++import { FormInlineUpdater } from "./FormInlineUpdater";++describe("FormInlineUpdater", () => {+ it("rolls back form values when an update fails", async () => {+ const error = new Error("Update failed");+ const update = jest.fn().mockRejectedValue(error);+ const onError = jest.fn();++ render(+ <FormProvider initialValues={{ enabled: false }} onSubmit={jest.fn()}>+ <Form>+ <FormInlineUpdater update={update} onError={onError} debounceMs={0} />+ <FormSwitch name="enabled" label="Enabled" />+ </Form>+ </FormProvider>,+ );++ const enabledSwitch = screen.getByRole("switch", { name: "Enabled" });+ await userEvent.click(enabledSwitch);++ await waitFor(() => {+ expect(update).toHaveBeenCalledWith({ enabled: true });+ });+ await waitFor(() => {+ expect(enabledSwitch).not.toBeChecked();+ });+ expect(onError).toHaveBeenCalledWith(error);+ });++ it("rolls back to the latest successful values", async () => {+ const error = new Error("Update failed");+ const update = jest+ .fn()+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(error);+ const onError = jest.fn();++ render(+ <FormProvider+ initialValues={{ enabled: false, archived: false }}+ onSubmit={jest.fn()}+ >+ <Form>+ <FormInlineUpdater update={update} onError={onError} debounceMs={0} />+ <FormSwitch name="enabled" label="Enabled" />+ <FormSwitch name="archived" label="Archived" />+ </Form>+ </FormProvider>,+ );++ const enabledSwitch = screen.getByRole("switch", { name: "Enabled" });+ const archivedSwitch = screen.getByRole("switch", { name: "Archived" });++ await userEvent.click(enabledSwitch);+ await waitFor(() => {+ expect(update).toHaveBeenNthCalledWith(1, {+ enabled: true,+ archived: false,+ });+ });++ await userEvent.click(archivedSwitch);+ await waitFor(() => {+ expect(update).toHaveBeenNthCalledWith(2, {+ enabled: true,+ archived: true,+ });+ });+ await waitFor(() => {+ expect(enabledSwitch).toBeChecked();+ expect(archivedSwitch).not.toBeChecked();+ });+ expect(onError).toHaveBeenCalledWith(error);+ });++ it("rolls back to reinitialized values", async () => {+ const error = new Error("Update failed");+ const update = jest.fn().mockRejectedValue(error);+ const onError = jest.fn();+ const renderForm = (initialValues: {+ enabled: boolean;+ archived: boolean;+ }) => (+ <FormProvider+ initialValues={initialValues}+ onSubmit={jest.fn()}+ enableReinitialize+ >+ <Form>+ <FormInlineUpdater update={update} onError={onError} debounceMs={0} />+ <FormSwitch name="enabled" label="Enabled" />+ <FormSwitch name="archived" label="Archived" />+ </Form>+ </FormProvider>+ );++ const { rerender } = render(+ renderForm({ enabled: false, archived: false }),+ );+ rerender(renderForm({ enabled: true, archived: false }));++ const enabledSwitch = screen.getByRole("switch", { name: "Enabled" });+ const archivedSwitch = screen.getByRole("switch", { name: "Archived" });+ await waitFor(() => {+ expect(enabledSwitch).toBeChecked();+ });++ await userEvent.click(archivedSwitch);+ await waitFor(() => {+ expect(update).toHaveBeenCalledWith({ enabled: true, archived: true });+ });+ await waitFor(() => {+ expect(enabledSwitch).toBeChecked();+ expect(archivedSwitch).not.toBeChecked();+ });+ expect(onError).toHaveBeenCalledWith(error);+ });+});