Skip to content

Instantly share code, notes, and snippets.

@lukebrandonfarrell
Created October 3, 2019 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukebrandonfarrell/e5a21b520104973d966489725083de36 to your computer and use it in GitHub Desktop.
Save lukebrandonfarrell/e5a21b520104973d966489725083de36 to your computer and use it in GitHub Desktop.
Sets an array of errors for a formik form
/*
* 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" });
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