Reputation: 28810
I have this code.
export const PostcodeFinder: React.FC = () => {
const {
postcodeSearch,
isLoading,
data,
isPending,
error: fetchError,
} = usePostcodeSearch();
return (
<Formik
validate={(values) => {
// will be ran before the `fetchError` is set from async response
if (fetchError) {
return { postcode: fetchError };
}
return {};
}}
The problem is that validate is called onChange or when the form is submitted so it runs before the async response has returned.
How can I set the validation error from an async response in formik?
Upvotes: 1
Views: 1207
Reputation: 22885
You need to return a promise which will resolve to errors object { someKey: 'some message' }
<Formik
validate={async (values) => {
const resp = fetch(`/validateEmailExists?email=${values.email}`);
const data = await resp.json();
if (data.emailExists) {
return { email: data.message /* it can be your own custom message */ };
}
return {};
}}
Upvotes: 1