forked from saleor/storefront
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add keeping values and dirty in useForm for autocomplete to work (sal…
- Loading branch information
Magdalena Markusik
authored
Feb 24, 2023
1 parent
2497360
commit 28cb9cd
Showing
1 changed file
with
30 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,51 @@ | ||
import { FormDataBase, FormProps, UseFormReturn } from "@/checkout-storefront/hooks/useForm/types"; | ||
import { | ||
ChangeHandler, | ||
FormDataBase, | ||
FormProps, | ||
UseFormReturn, | ||
} from "@/checkout-storefront/hooks/useForm/types"; | ||
import { useFormik, useFormikContext } from "formik"; | ||
import { useCallback } from "react"; | ||
import { isEqual } from "lodash-es"; | ||
import { useCallback, useState } from "react"; | ||
|
||
export const useForm = <TData extends FormDataBase>({ | ||
initialDirty, | ||
initialDirty = false, | ||
...formProps | ||
}: FormProps<TData>): UseFormReturn<TData> => { | ||
const form = useFormik<TData>(formProps); | ||
// we do this because in some cases it's not updated properly | ||
// https://github.com/jaredpalmer/formik/issues/3165 | ||
const [dirty, setDirty] = useState(initialDirty); | ||
const [values, setValues] = useState(formProps.initialValues); | ||
|
||
const { dirty, handleSubmit: handleFormikSubmit } = form; | ||
const { handleSubmit: handleFormikSubmit, handleChange: formikHandleChange } = form; | ||
|
||
const handleSubmit = useCallback( | ||
(event?: React.FormEvent<HTMLFormElement>) => { | ||
event?.preventDefault(); | ||
|
||
// we do it here because formik doesn't pass props like dirty to onSubmit | ||
if (initialDirty || dirty) { | ||
if (dirty) { | ||
handleFormikSubmit(event); | ||
} | ||
}, | ||
[dirty, handleFormikSubmit, initialDirty] | ||
[dirty, handleFormikSubmit] | ||
); | ||
|
||
return { ...form, handleSubmit }; | ||
const handleChange: ChangeHandler = useCallback( | ||
(event) => { | ||
const { name, value } = event.target; | ||
|
||
const updatedValues = { ...values, [name]: value }; | ||
|
||
setDirty(!isEqual(values, updatedValues)); | ||
setValues(updatedValues); | ||
formikHandleChange(event); | ||
}, | ||
[formikHandleChange, values] | ||
); | ||
|
||
return { ...form, handleSubmit, handleChange, values, dirty }; | ||
}; | ||
|
||
export const useFormContext = useFormikContext; |