How to write response from API into Formik form?
P粉546257913
P粉546257913 2023-08-17 17:33:34
0
2
462
<p>How to write the API response to Formik? I have an API through which I receive data that matches my form exactly, how do I write the entire response at once instead of using multiple setFieldValue lines? </p> <pre class="brush:php;toolbar:false;">const form = useFormik({ initialValues: { name: "", login: "", about: { age: "", rank: { silver: true, gold: false, global: false } } } }); // My initial form const { values, handleChange, setFieldValue, } = form; useEffect(() => { if (!isEmpty(projectData)) { Object?.keys(projectData)?.map((item: any, idx: number) => { const key: any = Object.keys(item).at(-1); setFieldValue(key, item[key]); }); } }, [projectData]); // Set API response</pre>
P粉546257913
P粉546257913

reply all(2)
P粉283559033

You need to set enableReinitialize to allow Formik to update the value when it changes.

const form = useFormik({
    initialValues: ...,
    enableReinitialize: true //<-- 这里
});

You can also set the value directly at one time in useEffect.

useEffect(() => {
    if (projectData && .../*其他条件*/) {
        form.setValues(projectData)
    }
}, [projectData])
P粉176203781

If the structure of the data received from the API matches the structure of the form, you can use the setValues method to set the entire state at once.

Make sure the data structure from the API response (projectData) matches the structure of your initialValues.

Use the setValues method to update all values ​​at once.

const form = useFormik({
  initialValues: {
    name: "",
    login: "",
    about: {
      age: "",
      rank: {
        silver: true,
        gold: false,
        global: false
      }
    }
  }
});

const { setValues } = form;

useEffect(() => {
  if (projectData) {
    setValues(projectData);
  }
}, [projectData]); // 设置来自API的响应
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template