Search code examples
reactjsformik

How to set all formik values at once?


I have a formik form for editing data which comes from an API endpoint,currently I am re-initializing the values in a useEffect hook like this

React.useEffect(() => {
    initialValues.first_name = address?.first_name;
    initialValues.last_name = address?.last_name;
    initialValues.middle_name = address?.middle_name;
    initialValues.label = address?.label;
    initialValues.description = address?.description;
  }, [address, initialValues]);

since the form has many values the useEffect hook gets lengthy and does not look clean either, I am trying to find a way to do it in a single line so it does not get a giant piece of code.


Solution

  • so it worked when I used formik.setValues, since it returns a promise so I put it in an asynchronous function. formik.setValues

      React.useEffect(() => {
        async function setInitialValues() {
          if (address) await formik.setValues(address, false);
        }
        setInitialValues();
    
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [address]);