How to write response from api to formik?
I have an api by which I receive data, this data is completely consistent with my form, how can I immediately write the entire response so as not to make many setFieldValue lines?
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 response api
2
Answers
You have to set
enableReinitialize
to allow Formik to update the values upon changes.You can, also, directly set the values in a single go in your
useEffect
.If the shape of the data you’re receiving from the API matches the structure of your form, you can set the entire state at once using the
setValues
method.Make sure the data structure from your API response (
projectData
) matches the structure of yourinitialValues
.Use the
setValues
method to update all the values at once.