Skip to content

Commit

Permalink
Custom OnChange vs Field change
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnyomair committed Jun 17, 2024
1 parent 7596ac2 commit d473756
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion storybook/src/admin/form/DependentAsyncSelects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AsyncSelectField, FinalForm } from "@comet/admin";
import { Box } from "@mui/material";
import { storiesOf } from "@storybook/react";
import * as React from "react";
import { OnChange } from "react-final-form-listeners";
import { Field, FieldRenderProps } from "react-final-form";

import { apolloStoryDecorator } from "../../apollo-story.decorator";
import { Manufacturer, Product } from "../../mocks/handlers";
Expand Down Expand Up @@ -72,12 +72,40 @@ storiesOf("@comet/admin/form", module)
/>
<OnChange name="manufacturer">
{() => {
console.log("Custom OnChange");
form.change("product", undefined);
return null;
}}
</OnChange>
<Field name="manufacturer" subscription={{ value: true, dirty: true }}>
{() => {
console.log("Field change");
form.change("product", undefined);
return null;
}}
</Field>
</>
)}
</FinalForm>
</Box>
);
});

type Props = { name: string; children: (value: any, previous: any) => void };

function OnChange({ name, children }: Props) {
return <Field name={name}>{({ input }) => <InnerOnChange input={input}>{children}</InnerOnChange>}</Field>;
}

function InnerOnChange({ input, children }: Pick<FieldRenderProps<any>, "input"> & Pick<Props, "children">) {
const previousValue = React.useRef(input.value);

React.useEffect(() => {
if (input.value !== previousValue.current) {
children(input.value, previousValue.current);
previousValue.current = input.value;
}
}, [input.value, children]);

return null;
}

0 comments on commit d473756

Please sign in to comment.