From d9ff7b15a19679be2fafd596c934e1b6e705f99a Mon Sep 17 00:00:00 2001 From: Brendan Wong <35351983+LunrEclipse@users.noreply.github.com> Date: Wed, 2 Aug 2023 16:04:50 -0400 Subject: [PATCH] fix: swap flashing the wrong value after the input is cleared. (#6719) * fix: set input panel to 0 when recalculating * fix: only reset number when input cleared * fix: remove useEffect and more graciously handle trade mutation --- src/state/swap/hooks.tsx | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/state/swap/hooks.tsx b/src/state/swap/hooks.tsx index a0c42ea6a0..0753c8a4e7 100644 --- a/src/state/swap/hooks.tsx +++ b/src/state/swap/hooks.tsx @@ -5,7 +5,7 @@ import useAutoSlippageTolerance from 'hooks/useAutoSlippageTolerance' import { useBestTrade } from 'hooks/useBestTrade' import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount' import { ParsedQs } from 'qs' -import { ReactNode, useCallback, useEffect, useMemo } from 'react' +import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react' import { AnyAction } from 'redux' import { useAppDispatch } from 'state/hooks' import { InterfaceTrade, TradeState } from 'state/routing/types' @@ -89,6 +89,7 @@ export type SwapInfo = { // from the current swap inputs, compute the best trade and return it. export function useDerivedSwapInfo(state: SwapState, chainId: ChainId | undefined): SwapInfo { const { account } = useWeb3React() + const [previouslyInvalid, setPreviouslyInvalid] = useState(false) const { independentField, @@ -114,7 +115,7 @@ export function useDerivedSwapInfo(state: SwapState, chainId: ChainId | undefine [inputCurrency, isExactIn, outputCurrency, typedValue] ) - const trade = useBestTrade( + let trade = useBestTrade( isExactIn ? TradeType.EXACT_INPUT : TradeType.EXACT_OUTPUT, parsedAmount, (isExactIn ? outputCurrency : inputCurrency) ?? undefined, @@ -122,6 +123,25 @@ export function useDerivedSwapInfo(state: SwapState, chainId: ChainId | undefine account ) + const nextPreviouslyInvalid = (() => { + if (trade.state === TradeState.INVALID) { + return true + } else if (trade.state !== TradeState.LOADING) { + return false + } + return undefined + })() + if (typeof nextPreviouslyInvalid === 'boolean' && nextPreviouslyInvalid !== previouslyInvalid) { + setPreviouslyInvalid(nextPreviouslyInvalid) + } + + if (trade.state == TradeState.LOADING && previouslyInvalid) { + trade = { + ...trade, + trade: undefined, + } + } + const currencyBalances = useMemo( () => ({ [Field.INPUT]: relevantTokenBalances[0],