0
   <Formik
        enableReinitialize
        initialValues={testState}
        validateOnChange
        onSubmit={onSubmit}>
            {(formProps) => {
              formProps.dirty && !isEmpty(formProps.touched) && handleFormDirty();
              return (
                <TestComponent />
              );
            }}
     </Formik>

handleFormDirty is a function from React context, which will change the state in React context. However, when I try to invoke handleFormDirty, it will show warnings like:

To locate the bad setState() call inside Formik, follow the stack trace as described

I found a similar question here setState called in render prop is causing a react warning but it seems like the answer is not perfect.

Any ideas? Thanks a lot.

Yang Wang
  • 580
  • 4
  • 14
  • Why are you calling it on every render? What does it actually do? – Adam Jenkins Aug 01 '21 at 01:31
  • I need to pop a modal when I click cancel button or breadcrumb link to leave the page when the form gets dirty and touched. Then I use handleFormDirty to change state isFormdirty. – Yang Wang Aug 01 '21 at 01:56

1 Answers1

1

Do it in an effect. You can't update state at the same time as render:


const ParentComponent = (props) => {

   return (
     <Formik
        enableReinitialize
        initialValues={testState}
        validateOnChange
        onSubmit={onSubmit}
     >
          {(formProps) => <MyFormComponent {...formProps} handleDirty={handleFormDirty}/>}
     </Formik>
   );
}


const MyFormComponent = ({handleDirty,...formProps}) => {

  useEffect(() => {
    formProps.dirty && !isEmpty(formProps.touched) && handleFormDirty();
  },[formProps.touched,formProps.dirty,handleDirty]);

  return (
    <TestComponent/>
  );


}

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100