Created
October 3, 2019 13:50
-
-
Save lukebrandonfarrell/e5a21b520104973d966489725083de36 to your computer and use it in GitHub Desktop.
Sets an array of errors for a formik form
This file contains hidden or 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
/* | |
* The first arguement is an object of errors e.g. { email: "Email has been taken" } | |
* The seound arguement is a refrence to your formik form (e.g. useRef) | |
* The third arguement is an optional mapping | |
*/ | |
useSetFormikErrors(errors, formikRef, { dob: "birthday" }); |
This file contains hidden or 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 { useRef, useEffect } from "react"; | |
import { useStore } from "react-redux"; | |
import _castArray from "lodash.castarray"; | |
import useEffectAfterMount from "./useEffectAfterMount.js"; | |
/** | |
* Sets a array of errors for formik form via a ref | |
* | |
* @param errors | |
* @param ref - reference to formik component | |
* @param map - maps error keys to the correct fields | |
*/ | |
export function useSetFormikErrors(errors, ref, map) { | |
useEffect( | |
() => { | |
/* | |
* Maps keys to the correct filed names, e.g. if | |
* we supply a map of { firstName: "newFieldName" } | |
* the 'firstName' error will be set on the 'newFieldName' | |
* field. | |
*/ | |
const mappedErrors = _mapKeys(errors, (value, key) => { | |
return _get(map, key, key) || key; | |
}); | |
ref.current.setErrors(mappedErrors); | |
}, | |
[errors] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment