Skip to content

Commit

Permalink
feat: add automatic formik form submission, fixes old values in formi…
Browse files Browse the repository at this point in the history
…k onChange function
  • Loading branch information
LiineKasak committed Aug 27, 2024
1 parent 2c9c441 commit d495c30
Show file tree
Hide file tree
Showing 4 changed files with 155 additions and 69 deletions.
152 changes: 83 additions & 69 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"@fortawesome/react-fontawesome": "^0.2.0",
"autoprefixer": "^10.0.0",
"dayjs": "^1.0.0",
"debounce": "^2.1.0",
"formik": "^2.2.9",
"postcss-import": "^15.1.0",
"react": "^18.2.0",
Expand Down
35 changes: 35 additions & 0 deletions src/forms/FormikAutoSubmit.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Form, Formik } from 'formik'
import React from 'react'
import FormikAutoSubmit from './FormikAutoSubmit'
import FormikTextField from './NewFormikTextField'

export const Default = () => (
<div>
<div>
Formik with an AutoSubmit component calls onSubmit with a given debounce
(here 1000)
</div>
<Formik
initialValues={{
name: '',
}}
isInitialValid={false}
onSubmit={async (values) => {
alert(`Form submitted with value: ${values.name}`)
}}
>
<div>
<Form>
<FormikAutoSubmit debounceWait={1000} />
<FormikTextField
name="name"
label="Label"
tooltip="Tooltip for this input"
className={{ root: 'mb-1 w-80' }}
placeholder="Placeholder"
/>
</Form>
</div>
</Formik>
</div>
)
36 changes: 36 additions & 0 deletions src/forms/FormikAutoSubmit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// https://github.com/jaredpalmer/formik/issues/2769#issuecomment-1872382784

import debounce from 'debounce'
import { useFormikContext } from 'formik'
import { useEffect, useMemo } from 'react'

export interface AutoSubmitProps {
debounceWait: number
}

export function FormikAutoSubmit({ debounceWait }: AutoSubmitProps) {
/*
This component is used to automatically submit the form when the form is valid
and has been changed(dirty).
*/
const { isValid, values, dirty, submitForm } = useFormikContext()

// avoid repetitive calls to debounce
const debouncedSubmit = useMemo(
() =>
debounce(() => {
if (isValid && dirty) {
void submitForm()
}
}, debounceWait),
[isValid, dirty, submitForm, debounceWait]
)

useEffect(() => {
debouncedSubmit()
}, [isValid, values, dirty, submitForm, debouncedSubmit])

return null
}

export default FormikAutoSubmit

0 comments on commit d495c30

Please sign in to comment.