Formik - TypeError: Cannot read property 'type' of undefined?
12,935
Solution 1
Instead of field.onChange use setFieldValue helper function
field.onChange(field.name)(Array.from(set)); //the problem seems to lie here somewhere!
replace with:
form.setFieldValue(field.name,(Array.from(set)));
https://codesandbox.io/embed/formik-checkbox-example-l9p1p?fontsize=14&hidenavigation=1&theme=dark
Solution 2
If anyone stumbles across this with a basic from producing the above error, it could be because you missed adding initialValues
to Formik
component.
Just fix it by adding
<Formik initialValues={{}} onSubmit={handleSubmit}>
This fixed it for me!
Related videos on Youtube
Author by
R. Kohlisch
Updated on June 04, 2022Comments
-
R. Kohlisch almost 2 years
I've pretty much just copy pasted this code from here :
function Checkbox(props) { return ( <Field name={props.name}> {({ field, form }) => ( <label> <input {...field} type="checkbox" checked={field.value.includes(props.value)} onChange={() => { const set = new Set(field.value); if (set.has(props.value)) { set.delete(props.value); } else { set.add(props.value); } field.onChange(field.name)(Array.from(set)); //the problem seems to lie here somewhere! form.setFieldTouched(field.name, true); }} /> {props.value} </label> )} </Field> ); } function App() { return ( <Formik initialValues={{ roles: [] }} onSubmit={values => alert(JSON.stringify(values, null, 2))} > {formik => ( <div> Clicking checks affects `VALUES` and `ERRORS` but never `TOUCHED`... <div> <Checkbox name="roles" value="admin" /> <Checkbox name="roles" value="customer" /> </div> <br /> VALUES: <pre>{JSON.stringify(formik.values, null, 2)}</pre> ERRORS: <pre>{JSON.stringify(formik.errors, null, 2)}</pre> TOUCHED: <pre>{JSON.stringify(formik.touched, null, 2)}</pre> </div> )} </Formik> ); }
The Sandbox seems to be working, but whenever I check a checkbox locally, I get
TypeError: Cannot read property 'type' of undefined
TypeError: Cannot read property 'type' of undefined (anonymous function) node_modules/formik/dist/formik.esm.js:659 656 | dispatch({ 657 | type: 'SET_ERRORS', 658 | payload: errors > 659 | }); 660 | }, []); 661 | var setValues = useEventCallback(function (values) { 662 | dispatch({
Not sure what I've done wrong here?
-
Akash Sarode almost 3 yearsyes, adding initialValues back fixed it for me.
-
5uperdan about 2 yearsThis does fix the problem, though the console generates a different warning: "Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen.". I don't know if the form will continue to work as expected, but it seems like if you want the initial field values to all be blank, it's better to specify that explicitly. e.g. initialValues={{"field1": "", etc...}}