From ae879edce27e0727289150721c92fd13bb410ee1 Mon Sep 17 00:00:00 2001 From: Volodymyr Gerun Date: Tue, 9 Jul 2024 09:40:01 +0300 Subject: [PATCH] feat(edit transaction): not submit without changes --- app/ui/transaction-form-edit.tsx | 33 ++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/app/ui/transaction-form-edit.tsx b/app/ui/transaction-form-edit.tsx index 9a58566..ae920b2 100644 --- a/app/ui/transaction-form-edit.tsx +++ b/app/ui/transaction-form-edit.tsx @@ -48,6 +48,8 @@ function TransactionFormEdit({ transaction }: TProps) { Array.from(category)[0]?.toString(), ) const currency = transaction.currency + const isEdited = transaction.isEdited + const transactionId = transaction.id const onChangeDescription = (e: React.ChangeEvent) => { setDescription(e.target.value) @@ -64,19 +66,46 @@ function TransactionFormEdit({ transaction }: TProps) { } } + const hasChanges = ( + newData: Partial, + oldData: TTransaction, + ) => { + const { amount, ...restOldData } = oldData + const modifiedOldData: TTransaction = { + ...restOldData, + amount: getFormattedCurrency(oldData.amount), + } + return Object.keys(newData).some((key) => { + const newKey = key as keyof typeof newData + return ( + newData[newKey] !== undefined && + newData[newKey] !== modifiedOldData[newKey] + ) + }) + } + const onSubmit = async (e: React.FormEvent) => { e.preventDefault() setIsLoading(true) + const newTransactionData = { isIncome: isSwitchedOn, - isEdited: true, + isEdited, description, amount, category: categoryWithEmoji, currency, } + + if (!hasChanges(newTransactionData, transaction)) { + toast.error('No changes detected.') + setIsLoading(false) + return + } + newTransactionData.isEdited = true + try { - await editTransactionById(transaction.id, newTransactionData) + await editTransactionById(transactionId, newTransactionData) router.push(ROUTE.HOME) toast.success('Transaction edited.') } catch (err) {