jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
34.01k stars 2.79k forks source link

Formik lost it state after history.goBack() #2412

Open jitenderchand1 opened 4 years ago

jitenderchand1 commented 4 years ago

🐛 Bug report

Current Behavior

When I do history.goBack() the component shows up for a second then hide itself. I used formikProps.dirty to determine whether to show prompt but the Formik rerender itself again and set formikProps.dirty to false when I do history.goBack()

Expected behavior

While rerendering Formik should not retain state

Reproducible example

I am using react-router-navigation-prompt to warn the user to save unsaved changes.

           <Formik
                validate={this.validateForm}
                enableReinitialize
                initialValues={initialValues}
                onSubmit={this.handleCreateUpdateUserFormSubmit}
                component={(formikProps: FormikProps<IFormValues>) => {
                  console.log('chand', formikProps.dirty)
                  return (
                    <>
                      <Prompt when={formikProps.dirty} />
                      <UserEditorForm
                        {...formikProps}
                        {...this.props}
                        rolesList={this.props.rolesList}
                        goBack={this.goBack}
                        isEdit={isEdit}
                      />
                    </>
                  );
                }}
              />

Your environment

Software Version(s)
Formik 2.1.4
React ^16.13.1
TypeScript ^3.8.3
Browser chrome
Yarn 1.13.0
Operating System Mac OS
johnrom commented 4 years ago

Formik should not lose its state if the page isn't physically reloaded and if it and every one of its ancestors retains the same identity in the hierarchy between renders, independent of what happens in React Router. That said, React Router might be switching a parent in the hierarchy, like the page template. If the only components that change are the Siblings of Formik, this can be solved by adding a key={} to Formik that doesn't change. If any of Formik's ancestors changes component types or ends up with a different key={}, there is no way to retain Formik's state, and it would have to be managed outside of React State (redux, etc), or the Formik component moved outside of the changing hierarchy.

I can't really give any more insight without a minimal CodeSandbox reproduction of your issue.