Skip to content

Commit

Permalink
Add keeping values and dirty in useForm for autocomplete to work (sal…
Browse files Browse the repository at this point in the history
  • Loading branch information
Magdalena Markusik authored Feb 24, 2023
1 parent 2497360 commit 28cb9cd
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions packages/checkout-storefront/src/hooks/useForm/useForm.ts
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;

0 comments on commit 28cb9cd

Please sign in to comment.