Created
September 18, 2020 14:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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