Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/
import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { TFunction, useTranslation } from 'react-i18next';
import clsx from 'clsx';
Expand Down Expand Up @@ -100,15 +101,26 @@ export default function ProductForm({
onActionButtonClick,
onCancel,
}: ProductFormProps) {
const [isSaving, setIsSaving] = useState(false);

const { t } = useTranslation();
const formMethods = useForm<ProductFormFields>({ mode: 'onBlur' });
const isAdmin = useSelector(isAdminSelector);

const saveProduct = useSaveProduct({ formMode: mode, productFormType });

const onSave = () => {
setIsSaving(true);

const onSuccess = () => {
onCancel();
setIsSaving(false);
};

const onError = () => setIsSaving(false);

formMethods.handleSubmit((data) => {
saveProduct?.(data, onCancel);
saveProduct?.(data, onSuccess, onError);
})();
};

Expand Down Expand Up @@ -152,7 +164,7 @@ export default function ProductForm({
informationalText={
mode === FormMode.EDIT ? t('ADD_PRODUCT.BUTTON_WARNING') : undefined
}
isDisabled={!formMethods.formState.isValid}
isDisabled={!formMethods.formState.isValid || isSaving}
onConfirm={onSave}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ const useSaveProduct = ({ formMode, productFormType }: UseSaveProductProps) => {

const onSave = async (
data: SoilAmendmentProductFormAllFields,
callback: (product_id: ProductId) => void = () => {},
onSuccess: (product_id: ProductId) => void = () => {},
onError?: () => void,
) => {
if (!formMode || !productFormType) {
return;
Expand All @@ -105,6 +106,7 @@ const useSaveProduct = ({ formMode, productFormType }: UseSaveProductProps) => {
console.error(e);
const message = isNew ? t('message:PRODUCT.ERROR.CREATE') : t('message:PRODUCT.ERROR.UPDATE');
dispatch(enqueueErrorSnackbar(message));
onError?.();
return;
}

Expand All @@ -115,7 +117,7 @@ const useSaveProduct = ({ formMode, productFormType }: UseSaveProductProps) => {
dispatch(enqueueSuccessSnackbar(message));

// Set product_id for the newly created product. Should be called after getProducts()
callback(result.product_id);
onSuccess(result.product_id);
};

dispatch(getProducts({ callback: onProductsFetched }));
Expand Down