search

Home  >  Q&A  >  body text

How to write response from API into Formik form?

<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粉546257913P粉546257913453 days ago451

reply all(2)I'll reply

  • P粉283559033

    P粉2835590332023-08-18 15:20:03

    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])
    

    reply
    0
  • P粉176203781

    P粉1762037812023-08-18 12:57:56

    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的响应

    reply
    0
  • Cancelreply