How to write response from API into Formik form?
P粉546257913
2023-08-17 17:33:34
<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>
You need to set
enableReinitialize
to allow Formik to update the value when it changes.You can also set the value directly at one time in
useEffect
.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 yourinitialValues
.Use the
setValues
method to update all values at once.