Skip to content

Commit

Permalink
fix(formiks): initialize FormikCheckbox form value on mount
Browse files Browse the repository at this point in the history
  • Loading branch information
ivangabriele committed Feb 9, 2023
1 parent e63499a commit 741505f
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/formiks/FormikCheckbox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useField } from 'formik'
import { useMemo } from 'react'
import { useEffect, useMemo } from 'react'

import { Checkbox } from '../fields/Checkbox'

Expand All @@ -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 (
<Checkbox
defaultChecked={isDefaultChecked}
Expand Down

0 comments on commit 741505f

Please sign in to comment.