Danielle
Danielle

Reputation: 59

React + Formik - how to pass in new values and set form as dirty?

I have a Formik form in my React app and I have a specific scenario I can't seem to find a workaround for:

I have a toggle outside of my custom form component that essentially "sets everything in the form to false". My current solution is when that gets toggled, I update the props I'm passing to form component, and re-rendering:

In my Form component:

const [initialState, setInitialState] = useState(props.initialState);

useEffect(() => {
  setInitialState(props.initialState);
}, [props.initialState]);

...
...

<Formik
  enableReinitialize
  initialState={initialState}
  ...
/>

This does correctly update my form with the new values, but it doesn't set the form to be dirty. I have logic in my form component based on whether it is dirty, and in this scenario I want the form to be considered dirty. I first tried to set each field to be touched or include each one in initialTouched. However, dirty is computed comparing current values to initialState, not whether fields have been touched, so my form here is considered "pristine" because it is literally the same as my (new) initial state.

What I'm looking for is either:

Upvotes: 2

Views: 7054

Answers (2)

sultanmyrza
sultanmyrza

Reputation: 5402

       onSubmit={(values, { setSubmitting, resetForm }) => {
          setSubmitting(true);
          setTimeout(async () => {
            console.log(values);

            // it will set formik.isDirty to false
            // it will also keep new values
            resetForm({ values });  

          }, 100);
        }}

Upvotes: 2

Taylor Burke
Taylor Burke

Reputation: 444

Have you tried using the onReset property? That should allow you to pass values from any source you want.

Upvotes: 0

Related Questions