From 741505f7a6705cec2fa439284dff04de43fce962 Mon Sep 17 00:00:00 2001 From: Ivan Gabriele Date: Thu, 9 Feb 2023 02:38:18 +0100 Subject: [PATCH] fix(formiks): initialize FormikCheckbox form value on mount --- src/formiks/FormikCheckbox.tsx | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/formiks/FormikCheckbox.tsx b/src/formiks/FormikCheckbox.tsx index 5bbac1f2a..71b677022 100644 --- a/src/formiks/FormikCheckbox.tsx +++ b/src/formiks/FormikCheckbox.tsx @@ -1,5 +1,5 @@ import { useField } from 'formik' -import { useMemo } from 'react' +import { useEffect, useMemo } from 'react' import { Checkbox } from '../fields/Checkbox' @@ -14,6 +14,17 @@ export function FormikCheckbox({ name, ...originalProps }: FormikCheckboxProps) // eslint-disable-next-line react-hooks/exhaustive-deps const isDefaultChecked = useMemo(() => Boolean(field.value), []) + // A checkbox must initialize its Formik value on mount: + // it wouldn't make sense to keep it as `undefined` since `undefined` means `false` in the case of a checkbox + useEffect( + () => { + helpers.setValue(isDefaultChecked) + }, + + // eslint-disable-next-line react-hooks/exhaustive-deps + [] + ) + return (