Open kneczaj opened 2 years ago
I created this hook to handle Textinputs and checkboxes, sharing it here in case it helps anyone 😊
import {useFormik} from 'formik';
import * as Yup from 'yup';
type FormValues = Record<string, string | boolean>;
export type FormProps<T extends FormValues> = {
initialValues: T;
onSubmit: (values: T) => void;
schema: Yup.ObjectShape;
};
/** Hook used to handle forms values, validations and submission */
export const useForm = <T extends FormValues>({
initialValues,
onSubmit,
schema,
}: FormProps<T>) => {
const {values, handleChange, handleSubmit, errors, setFieldValue} = useFormik(
{
initialValues,
onSubmit,
validationSchema: createSchemaObject(schema),
enableReinitialize: true,
validateOnBlur: false,
validateOnChange: false,
},
);
/**Same as handleChange but for boolean fields */
const handleToggle = (fieldName: keyof typeof initialValues) => {
const value = values[fieldName];
return setFieldValue(fieldName as string, !value);
};
return {
form: values,
handleChange,
handleToggle,
handleSubmit,
errors,
};
};
Feature request
Current Behavior
This is the interface of Formik's handle change:
The Field's
Value
can beany
like here:Just HTML
<input>
tag producesReact.ChangeEvent
what means that Formik cannot be attached with itshandleChange
function to a custom field which does not produce it.The error in the browser when I use it with e.g.
boolean
is:and it happens at this line:
https://github.com/jaredpalmer/formik/blob/b9cc2536a1edb9f2d69c4cd20ecf4fa0f8059ade/packages/formik/src/Formik.tsx#L611
Workaround which I currently use is:
Desired Behavior
A boolean should be possible to save with
handleChange
so I may not use the workaround.Suggested Solution
Please support signature
How to do it?
Instead of
if (!isString(eventOrTextValue))
check here https://github.com/jaredpalmer/formik/blob/b9cc2536a1edb9f2d69c4cd20ecf4fa0f8059ade/packages/formik/src/Formik.tsx#L600 this could be used:Who does this impact? Who is this for?
<input>
tagonChange
prop with(event: ChangeEvent) => void
signature, and exposeonChange
prop with<T>(val: T) => void
signatureDescribe alternatives you've considered
The workaround is the alternative.
Additional context
Noting