You cannot reset form values like that to initial values.
What you need to do is to use method resetForm()
from Formik form ref.
You provide only once what are initial values, and reset when ever you need to.
I forked your codesanbox and modified code.
https://codesandbox.io/s/formik-re-render-initialvalues-forked-i84sy
Here are parts of the code related to what you need to do
import React, { useState, useRef } from "react";
...
const Page = () => {
const formikRef = useRef();
const setValues = () => {
console.log("hh");
setInitialValues({ ...initialValues, age: 75 });
formikRef.current.resetForm();
};
...
return (
<div>
<button onClick={setValues}>API Call</button>
<Formik
ref={(ref) => {
formikRef.current = ref;
}}
initialValues={initialValues}
onSubmit={submit}
validationSchema={validationSchema}
enableReinitialize
>
...
</Formik>
</div>
);
};
EDIT
I added one more part that covers modifying initial values. First you need to set initialValues
and than do formikRef.current.resetForm()
.
NOTE
If you upgrade Formik to 2.x.x
ref
is changed to innerRef
:
<Formik
innerRef={(ref) => {
formikRef.current = ref;
}}
></Formik>;
setInitialValues({ ...initialValues, age: 75 });
. TheinitialValues
is{ name: 'Tom', age: 85 }
, so you're using the spread(...
) operator to spread theinitialValues
, overwriting only theage
property, whilst thename
property stays as 'Tom'. – KapobajzasetInitialValues({ ...initialValues, age: 75 });
to:setInitialValues({ name: /* get the value of the name text field */, age: 75 });
– Kapobajza