javascriptreactjstypeerrorformik

Formik - TypeError: Cannot read property 'type' of undefined?


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?


Solution

  • 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