1- import { useMemo , useState , useEffect } from 'react' ;
1+ import { useMemo , useState , useEffect , useRef } from 'react' ;
22import { toChecksumAddress } from 'ethereumjs-util' ;
33import { shallowEqual , useSelector } from 'react-redux' ;
44import { getCurrentChainId } from '../../../../../shared/modules/selectors/networks' ;
@@ -45,14 +45,43 @@ export default function useTokenExchangeRate(
4545 ? contractExchangeRates [ tokenAddress ] || exchangeRates [ tokenAddress ]
4646 : undefined ;
4747
48+ const isMounted = useRef ( true ) ;
49+
4850 useEffect ( ( ) => {
4951 if ( ! contractExchangeRate && tokenAddress ) {
5052 setExchangeRates ( ( prev ) => ( {
5153 ...prev ,
5254 [ tokenAddress ] : LOADING ,
5355 } ) ) ;
56+ fetchTokenExchangeRates ( nativeCurrency , [ tokenAddress ] , chainId )
57+ . then ( ( addressToExchangeRate ) => {
58+ if ( isMounted . current ) {
59+ setExchangeRates ( ( prev ) => ( {
60+ ...prev ,
61+ [ tokenAddress ] : addressToExchangeRate [ tokenAddress ] ?? FAILED ,
62+ } ) ) ;
63+ }
64+ } )
65+ . catch ( ( ) => {
66+ if ( isMounted . current ) {
67+ setExchangeRates ( ( prev ) => ( {
68+ ...prev ,
69+ [ tokenAddress ] : FAILED ,
70+ } ) ) ;
71+ }
72+ } ) ;
5473 }
55- } , [ contractExchangeRate , tokenAddress ] ) ;
74+ return ( ) => {
75+ isMounted . current = false ;
76+ } ;
77+ } , [
78+ exchangeRates ,
79+ chainId ,
80+ nativeCurrency ,
81+ tokenAddress ,
82+ selectedNativeConversionRate ,
83+ contractExchangeRate ,
84+ ] ) ;
5685
5786 return useMemo ( ( ) => {
5887 if ( ! selectedNativeConversionRate ) {
@@ -76,29 +105,12 @@ export default function useTokenExchangeRate(
76105 }
77106
78107 if ( ! contractExchangeRate ) {
79- fetchTokenExchangeRates ( nativeCurrency , [ tokenAddress ] , chainId )
80- . then ( ( addressToExchangeRate ) => {
81- setExchangeRates ( ( prev ) => ( {
82- ...prev ,
83- // TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31880
84- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
85- [ tokenAddress ] : addressToExchangeRate [ tokenAddress ] || FAILED ,
86- } ) ) ;
87- } )
88- . catch ( ( ) => {
89- setExchangeRates ( ( prev ) => ( {
90- ...prev ,
91- [ tokenAddress ] : FAILED ,
92- } ) ) ;
93- } ) ;
94108 return undefined ;
95109 }
96110
97111 return new Numeric ( contractExchangeRate , 10 ) . times ( nativeConversionRate ) ;
98112 } , [
99113 exchangeRates ,
100- chainId ,
101- nativeCurrency ,
102114 tokenAddress ,
103115 selectedNativeConversionRate ,
104116 contractExchangeRate ,
0 commit comments