I have the following component that takes a render prop that it passes values to a child component. Here is a codesandbox that shows the problem. Press submit and look at the console.
Here is the component:
export const FormContainer = function FormContainer<V>({
initialValues,
validate,
render,
...rest
}: FormContainerProps<V>) {
const [hasValidationError, setHasValidationError] = useState(false);
const dispatch = useDispatch();
useEffect(() => {
if (!hasValidationError) {
return;
}
scrollToValidationError();
() => setHasValidationError(false);
}, [hasValidationError]);
return (
<>
<Formik
>
{({
isSubmitting,
submitCount,
isValid,
errors,
values,
}: FormikProps<V>) => {
const invalid = !isValid;
const submitted = submitCount > 0;
if (submitCount > 0 && invalid) {
setHasValidationError(true);
}
return (
<>
<Form>
<div className={styles.form}>
{render({
values,
errors,
isSubmitting,
invalid,
submitCount,
})}
</div>
</Form>
</>
);
}}
</Formik>
</>
);
};
If there is a validation error then setHasValidationError
is called which causes this error from react
Warning: Cannot update a component (`FormContainer`) while rendering a different component (`Formik`). To locate the bad setState() call inside `Formik`, follow the stack trace as described in
in Formik (created by FormContainer)
in FormContainer (created by Home)
in Home (created by Context.Consumer)
in Route (created by App)
in Switch (created by App)
in Router (created by App)
in App
I'm not saying this warning is wrong. Calling setHasValidationError
does not seem ideal here but the call to scrollToValidationError();
that will get called in the initial useEffect
hook is async and it needs to go outside the render function.
What can I do?