Skip to content

Commit

Permalink
Creates a similar shouldUpdate funciton fast field internally uses an…
Browse files Browse the repository at this point in the history
…d calls the external shouldUpdate along with it to prevent the component not re-rendering in a few scenarios.
  • Loading branch information
deepakjosp committed Dec 11, 2024
1 parent 6584282 commit 2a22b00
Showing 1 changed file with 41 additions and 17 deletions.
58 changes: 41 additions & 17 deletions src/components/Editor/FormikEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,47 @@ const FormikEditor = (
...otherProps
},
ref
) => (
<FastField {...{ attachments, mentions, name, shouldUpdate, variables }}>
{({ field, form, meta }) => (
<Editor
{...{ attachments, mentions, name, ref, variables }}
error={meta.touched ? meta.error : ""}
initialValue={field.value}
onBlur={() => form.setFieldTouched(name, true)}
onChange={value => {
form.setFieldValue(name, value);
onChange?.(value);
}}
{...otherProps}
/>
)}
</FastField>
);
) => {
// Similar to the `shouldComponentUpdate` logic of FastField component.
// https://github.com/jaredpalmer/formik/blob/main/packages/formik/src/FastField.tsx#L75-L93
// Additionally calls the shouldUpdate function passed from the host application and compares to
// the rest of the values.
const internalShouldUpdate = (prevProps, nextProps) => {
const prevFormikProps = prevProps.formik;
const nextFormikProps = nextProps.formik;

return (
prevFormikProps.errors[name] !== nextFormikProps.errors[name] ||
prevFormikProps.touched[name] !== nextFormikProps.touched[name] ||
Object.keys(nextProps).length !== Object.keys(prevProps).length ||
prevFormikProps.isSubmitting !== nextFormikProps.isSubmitting ||
Boolean(shouldUpdate?.(prevProps, nextProps))
);
};

return (
<FastField
{...{ attachments, mentions, name, variables }}
shouldUpdate={internalShouldUpdate}
>
{({ field, form, meta }) => (
<Editor
{...{ attachments, mentions, name, ref, variables }}
error={meta.touched ? meta.error : ""}
initialValue={field.value}
onBlur={() => {
form.setFieldTouched(name, true);
}}
onChange={value => {
form.setFieldValue(name, value);
onChange?.(value);
}}
{...otherProps}
/>
)}
</FastField>
);
};

FormikEditor.displayName = "FormikNeetoEditor";

Expand Down

0 comments on commit 2a22b00

Please sign in to comment.