Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  65] [ 1]  / answers: 1 / hits: 8271  / 3 Years ago, thu, february 25, 2021, 12:00:00

I currently have a form I am building using formik. I am able to update each of the fields(name, email, phone) as expected. The issue I am running into is when I provide one of the formik intial values with a state value and update that state. The act of updating the state causes the form to completely reset the input fields Is there a way to update the test state without resetting the entire form?? My code is as follows:


import { useState } from "react";
import { Formik, FieldArray } from "formik";
import "./styles.css";

export default function App() {
const [test, setTest] = useState(null);
return (
<Formik
enableReinitialize
initialValues={{
test: test,
name: "",
email: "",
phone: ""
}}
>
{({
values,
touched,
errors,
handleChange,
handleBlur,
handleSubmit
}) => (
<>
<button onClick={() => setTest("something")}>Update State</button>
<br />
<input
placeholder="name"
type="text"
name="name"
value={values.name}
onChange={handleChange}
/>
<br />
<input
placeholder="email"
type="text"
name="email"
value={values.email}
onChange={handleChange}
/>
<br />
<input
placeholder="phone"
type="text"
name="phone"
value={values.phone}
onChange={handleChange}
/>
<>
<pre style={{ textAlign: "left" }}>
<strong>Values</strong>
<br />
{JSON.stringify(values, null, 2)}
</pre>
<pre style={{ textAlign: "left" }}>
<strong>Errors</strong>
<br />
{JSON.stringify(errors, null, 2)}
</pre>
</>
</>
)}
</Formik>
);
}



In order to replicate what I am talking about in the codesandbox first update the name, email, and phone number. Then hit the udate state button and everything will be reset


codesandbox https://codesandbox.io/s/wispy-sun-mzeuy?file=/src/App.js:0-1567


More From » reactjs

 Answers
7

This is because you are initializing the Formik component with enableReinitialize set to true:



enableReinitialize?: boolean


Default is false. Control whether Formik should reset the form if initialValues changes (using deep equality).



When the state variable test is updated, the formik-values are reinitialized to the values set in initialValues.




If you want this to work, I've forked your sandbox and modified it to use the formik hook (without enableReinitialize) in combination with a useEffect to manually update the value from state:


  const [test, setTest] = useState(null);
const { values, errors, handleChange, setFieldValue } = useFormik({
initialValues: {
test: test,
name: "",
email: "",
phone: ""
}
});

useEffect(() => {
setFieldValue("test", test);
}, [test]);

[#1735] Friday, February 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;