From 97f1a546be15068fb2dc6e036d1aa02cba37b3d5 Mon Sep 17 00:00:00 2001 From: Jagoda Berry Rybacka Date: Fri, 8 Dec 2023 14:40:03 +0100 Subject: [PATCH] Fix token input for typing balance value manually When user was typing the balance amount manually then input was not updating values correctly. We moved to `useCallback` instead of `useEffect` and fixed the condition for updating parent component with new values. --- .../components/Interface/TokenAmountInput.tsx | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/src/shared/components/Interface/TokenAmountInput.tsx b/src/shared/components/Interface/TokenAmountInput.tsx index 160a2806..b013082f 100644 --- a/src/shared/components/Interface/TokenAmountInput.tsx +++ b/src/shared/components/Interface/TokenAmountInput.tsx @@ -76,24 +76,28 @@ export default function TokenAmountInput({ [balance, onValidate] ) - useEffect(() => { - const textToBigIntAmount = - textAmount === "" ? null : userAmountToBigInt(textAmount) ?? 0n - - const bigIntToTextAmount = bigIntToPreciseUserAmount(balance) - - // As we may be loosing some precision, we need to compare the values. - // Clicking "Max" button may result in bigint that is too big to be - // represented as a float number. In this case we need to compare values to - // not override the external value that stores the bigint using greater precision. - if (textToBigIntAmount !== amount && textAmount !== bigIntToTextAmount) { - onChange(textToBigIntAmount) - } - - // Make sure this is working only one way: - // from the text provided by input to the parent component - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [textAmount, onChange]) + const internalOnChange = useCallback( + (newValue: string) => { + setTextAmount(newValue) + + const newValueBigIntAmount = + newValue === "" ? null : userAmountToBigInt(newValue) ?? 0n + + const balanceTextAmount = bigIntToPreciseUserAmount(balance) + + // As we may be loosing some precision, we need to compare the values. + // Clicking "Max" button may result in bigint that is too big to be + // represented as a float number. In this case we need to compare values to + // not override the external value that stores the bigint using greater precision. + if ( + newValueBigIntAmount !== amount && + (newValue !== balanceTextAmount || newValueBigIntAmount === balance) + ) { + onChange(newValueBigIntAmount) + } + }, + [amount, balance, onChange] + ) useEffect(() => { // Allow clearing the input from parent componentthis should be the only case @@ -115,7 +119,7 @@ export default function TokenAmountInput({ label={inputLabel} value={textAmount} disabled={disabled} - onChange={setTextAmount} + onChange={internalOnChange} validate={validate} rightComponent={