jaredpalmer / formik

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

Comparing initialValues from enableReinitialize and values in onSubmit #2192

Open tkrebs2 opened 4 years ago

tkrebs2 commented 4 years ago

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 commented 4 years ago

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.