Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Created September 18, 2020 14:28
Show Gist options
  • Save vishaltelangre/07c506493ed795d042dfae281a20498d to your computer and use it in GitHub Desktop.
Save vishaltelangre/07c506493ed795d042dfae281a20498d to your computer and use it in GitHub Desktop.
Get access to errors on submitting the Formik-powered form and act accordingly anywhere down the Formik children hierarchy #formik
import React, { useEffect } from "react";
import { useFormikContext } from "formik";
const FormikSubmitErrorMiddleware = ({ onSubmitError }) => {
const formikContext = useFormikContext();
const { submitCount, isSubmitting, isValid } = formikContext;
useEffect(() => {
if (
submitCount > 0 &&
!isSubmitting &&
!isValid &&
typeof onSubmitError === "function"
) {
onSubmitError(formikContext);
}
}, [submitCount, isSubmitting, isValid]);
return null;
};
export default FormikSubmitErrorMiddleware;
const SegmentItem = ({
collapsedTitle,
expandedTitle,
fieldNamePrefix,
collapsible = true,
deletable = true,
onDelete = () => {},
children,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div className="border-t first:border-b border-gray-300 py-4 last:py-0">
<FormikSubmitErrorMiddleware
onSubmitError={({ errors }) => {
if (get(errors, fieldNamePrefix)) {
setIsExpanded(true);
}
}}
/>
<SegmentItemHeader
title={isExpanded ? expandedTitle : collapsedTitle}
actions={
<SegmentItemActions
{...{ collapsible, deletable, onDelete, isExpanded }}
onToggleCollapse={() => setIsExpanded(!isExpanded)}
/>
}
/>
{isExpanded ? <div className="mt-4">{children}</div> : null}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment