Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparing initialValues from enableReinitialize and values in onSubmit #2192

Open
tkrebs2 opened this issue Jan 10, 2020 · 1 comment
Open
Labels

Comments

@tkrebs2
Copy link

tkrebs2 commented Jan 10, 2020

I have a form that uses enableReinitialize to hydrate my initialValues from an api call. I have a use case where I want/need to compare initialValues and values in onSubmit to determine what values to send in a request. I don't want to send values that don't differ from what's in initialValues.

        `<Formik
          enableReinitialize
          initialValues={{
            remoteEnabled: remoteEnabled,
            pubAddr: pubAddr,
            facilities: loggingFacilities
          }}
          onSubmit={async (values, { setSubmitting }) => {
            console.log("values in onSubmit", values);

            // initialValues is undefined below
            const { initialValues } = props;

            alert(JSON.stringify(values, null, 2));
            try {
              // compare initialValues and values
              setLoggingFacilities(values.facilities);
              const valuesToSend = values.facilities
                .filter((facility, i) => {
                  // Let's send only those that have just been disabled or enabled:
                  return (
                    facility &&
                    initialValues[i] &&
                    facility.enabled !== initialValues[i].enabled
                  );
                })
                .map(facility => ({
                  key: facility.facilityName,
                  value: facility.enabled
                }));
            } catch (error) {
              console.log("error catch", error);
            }`

Haven't had much feedback asking this question in various other places.
I have a codesanbox here

@zmeyc
Copy link

zmeyc commented Jan 18, 2020

They're undefined because in the code above anonymous dictionary is being passed to Formik's parameter named initialValues, no variable is being created. And they're not in props as well.

If I understood the problem correctly, simply declare & init a variable named initialValues above JSX code, pass it to Formik's initialValues param, then compare it memberwise with values in onSubmit.

@stale stale bot added the stale label Mar 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants