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
fix: user's input is overwritten by async form reinitializations (#67525)
Egor Grushin9daa5119f6ad
diff --git a/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js b/e2e/test/scenarios/actions/actions-reproductions.cy.spec.jsindex 0a10893afd7..6c919fff788 100644--- a/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js+++ b/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js@@ -323,7 +323,7 @@ describe("issue 51020", () => {dropTemporaryTable();});- it("should pass primary key attribute to execute action endpoint when it's populated with click behavior or URL (metabase#51020)", () => {+ it("should pass primary key attribute to execute action endpoint when primary key is called 'id' and it's populated with click behavior or URL (metabase#51020)", () => {cy.log("check when primary key parameter is populated with click behavior",);@@ -381,15 +381,20 @@ describe("issue 51020", () => {.click();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- cy.findByPlaceholderText("Search…").type("foo");+ /**+ * Without this wait, typing speed causes flakiness: fast typing switches to search tab+ * before picker content loads, so no folder is selected and "Everywhere" toggle doesn't appear.+ */+ cy.findByTestId("single-picker-view").should("be.visible");+ cy.findByRole("searchbox").type("foo");+ cy.findByText("Everywhere").click();cy.findByText("Foo").click();});+cy.findByTestId("run-button").click();cy.wait("@dataset");cy.button("Save").click();- H.modal()- .findByLabelText("Name")- .type("{backspace}{backspace}{backspace}Model 51020");+ H.modal().findByLabelText("Name").clear().type("Model 51020");H.modal().button("Save").click();cy.wait("@createCard");cy.wait("@getCard");@@ -415,7 +420,7 @@ describe("issue 51020", () => {dropTemporaryTable();});- it("should pass primary key attribute to execute action endpoint when it's populated with click behavior or URL (metabase#51020)", () => {+ it("should pass primary key attribute to execute action endpoint when primary key isn't called 'id' and it's populated with click behavior or URL (metabase#51020)", () => {cy.log("check when primary key parameter is populated with click behavior",);diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/context.tsxindex d56abc7934b..c73eff1e29b 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx@@ -1,3 +1,4 @@+import { useFormikContext } from "formik";import {type PropsWithChildren,createContext,@@ -7,6 +8,8 @@ import {useMemo,useState,} from "react";+import { usePrevious } from "react-use";+import { isEqual } from "underscore";import { getCurrentUser } from "metabase/admin/datamodel/selectors";import { useListRecentsQuery } from "metabase/api";@@ -59,6 +62,7 @@ export const SaveQuestionContext =** Thanks for coming to my TED talk.* */+export const SaveQuestionProvider = ({question,originalQuestion: latestOriginalQuestion,@@ -81,19 +85,9 @@ export const SaveQuestionProvider = ({? currentUser.personal_collection_id: userTargetCollection;- const [hasLoadedRecentItems, setHasLoadedRecentItems] = useState(false);- const { data: recentItems, isLoading } = useListRecentsQuery(- { context: ["selections"] },- { skip: hasLoadedRecentItems },- );- // We need to stop refetching recent items as the user makes selections in the ui that could cause a refetch- // This causes new initial values getting calculated, which combined with Formik's `enableReinitialize`- // prop, results in a dirty form getting values replaced within initial state.- useEffect(() => {- if (!isLoading) {- setHasLoadedRecentItems(true);- }- }, [isLoading]);+ const { data: recentItems } = useListRecentsQuery({+ context: ["selections"],+ });const lastSelectedEntityModel = useMemo(() => {return recentItems?.find(@@ -187,30 +181,30 @@ export const SaveQuestionProvider = ({initialValues={initialValues}onSubmit={handleSubmit}validationSchema={SAVE_QUESTION_SCHEMA}- enableReinitialize>{({ values, setValues }) => (- <SaveQuestionContext.Provider- value={{- question,- originalQuestion,- initialValues,- handleSubmit,- values,- setValues,- showSaveType,- multiStep,- targetCollection,- saveToDashboard,- }}- >- {children}- </SaveQuestionContext.Provider>+ <FormValuesPatcher nextValues={initialValues}>+ <SaveQuestionContext.Provider+ value={{+ question,+ originalQuestion,+ initialValues,+ handleSubmit,+ values,+ setValues,+ showSaveType,+ multiStep,+ targetCollection,+ saveToDashboard,+ }}+ >+ {children}+ </SaveQuestionContext.Provider>+ </FormValuesPatcher>)}</FormProvider>);};-export const useSaveQuestionContext = () => {const context = useContext(SaveQuestionContext);if (!context) {@@ -220,3 +214,48 @@ export const useSaveQuestionContext = () => {}return context;};++/**+ * Patches form values when `nextValues` change asynchronously (e.g., after API calls).+ *+ * Terminology:+ * - "changed": nextValues differs from prevValues (new data arrived)+ * - "untouched": formValues[key] === prevValues[key] (user hasn't edited this field)+ * - "modified": formValues[key] !== prevValues[key] (user has edited this field)+ *+ * For each changed field:+ * - If untouched → apply the new value (safe to update)+ * - If modified → preserve user's input (don't overwrite)+ *+ * Uses deep comparison to correctly handle nested object values.+ */+export const FormValuesPatcher = <T extends object>({+ nextValues,+ children,+}: PropsWithChildren<{ nextValues: T }>) => {+ const { values: formValues, setValues } = useFormikContext<T>();+ const prevValues = usePrevious(nextValues);++ useEffect(() => {+ if (!prevValues || isEqual(nextValues, prevValues)) {+ return;+ }+ const patches: Partial<T> = {};+ for (const key of Object.keys(nextValues) as (keyof T)[]) {+ if (isEqual(formValues[key], prevValues[key])) {+ /**+ * While comparison is deep, patching is shallow.+ * This works for SaveQuestionForm since all fields are primitives. If reused with nested+ * objects, consider implementing deep/recursive patching to preserve user edits+ * within nested structures.+ */+ patches[key] = nextValues[key];+ }+ }+ if (Object.keys(patches).length > 0) {+ setValues({ ...formValues, ...patches });+ }+ }, [nextValues, prevValues, formValues, setValues]);++ return children;+};diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsxindex 264435c6bd8..73c9a163b1b 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx@@ -1,3 +1,5 @@+import * as formik from "formik";+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {defaultAuditInfo,@@ -6,7 +8,7 @@ import {setupRecentViewsAndSelectionsEndpoints,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { render, renderWithProviders, screen, waitFor } from "__support__/ui";import Question from "metabase-lib/v1/Question";import type { Card } from "metabase-types/api";import {@@ -18,7 +20,11 @@ import {} from "metabase-types/api/mocks";import { createMockState } from "metabase-types/store/mocks";-import { SaveQuestionProvider, useSaveQuestionContext } from "./context";+import {+ FormValuesPatcher,+ SaveQuestionProvider,+ useSaveQuestionContext,+} from "./context";const TestComponent = () => {const { values, saveToDashboard } = useSaveQuestionContext();@@ -342,3 +348,78 @@ describe("SaveQuestionContext", () => {});});});++describe("FormValuesPatcher", () => {+ const setValuesSpy = jest.fn();+ const setup = (initialValue: unknown) => {+ jest.spyOn(formik, "useFormikContext").mockReturnValue({+ values: initialValue,+ setValues: setValuesSpy,+ } as unknown as formik.FormikContextType<unknown>);+ };++ beforeEach(() => {+ setValuesSpy.mockClear();+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("should patch untouched fields when nextValues change", () => {+ setup({ name: "initial", count: 1 });++ const { rerender } = render(+ <FormValuesPatcher nextValues={{ name: "initial", count: 1 }}>+ <div />+ </FormValuesPatcher>,+ );++ rerender(+ <FormValuesPatcher nextValues={{ name: "updated", count: 99 }}>+ <div />+ </FormValuesPatcher>,+ );++ expect(setValuesSpy).toHaveBeenCalledWith({ name: "updated", count: 99 });+ });++ it("should preserve user-modified fields when nextValues change", () => {+ setup({ name: "user typed", count: 1 });++ const { rerender } = render(+ <FormValuesPatcher nextValues={{ name: "initial", count: 1 }}>+ <div />+ </FormValuesPatcher>,+ );++ rerender(+ <FormValuesPatcher nextValues={{ name: "updated", count: 99 }}>+ <div />+ </FormValuesPatcher>,+ );++ expect(setValuesSpy).toHaveBeenCalledWith({+ name: "user typed",+ count: 99,+ });+ });++ it("should not patch anything when nextValues remain unchanged", () => {+ setup({ name: "initial", count: 1 });++ const { rerender } = render(+ <FormValuesPatcher nextValues={{ name: "initial", count: 1 }}>+ <div />+ </FormValuesPatcher>,+ );++ rerender(+ <FormValuesPatcher nextValues={{ name: "initial", count: 1 }}>+ <div />+ </FormValuesPatcher>,+ );++ expect(setValuesSpy).not.toHaveBeenCalled();+ });+});