1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-22 09:57:02 +01:00

Fix useTokenTracker useEffect bug (#9334)

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
Co-authored-by: Brad Decker <git@braddecker.dev>
This commit is contained in:
Dan J Miller 2020-09-02 16:49:04 -02:30 committed by GitHub
parent 3d4f1f45bd
commit ccb7eb3ab7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 3 deletions

View File

@ -0,0 +1,27 @@
import { useState, useLayoutEffect } from 'react'
import { isEqual } from 'lodash'
/**
* Given a value and a function to determine equality, return a
* referentially equal value if the equality function returns true.
* This hook is helpful in avoiding re-renders and effects running
* based on an object or value that always changes references but
* infrequently changes it's value. By default, uses isEqual from
* lodash. This is typically only useful with objects and arrays.
*
* @param {T} value - any value to check equality of
* @param {(T, T) => boolean} equalityFn - A function to determine equality
* @returns {T}
*/
export function useEqualityCheck (value, equalityFn = isEqual) {
const [computedValue, setComputedValue] = useState(value)
useLayoutEffect(() => {
if (!equalityFn(value, computedValue)) {
setComputedValue(value)
}
}, [value, equalityFn, computedValue])
return computedValue
}

View File

@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react'
import TokenTracker from '@metamask/eth-token-tracker'
import { useSelector } from 'react-redux'
import { getCurrentNetwork, getSelectedAddress } from '../selectors'
import { useEqualityCheck } from './useEqualityCheck'
export function useTokenTracker (tokens) {
const network = useSelector(getCurrentNetwork)
@ -11,6 +12,7 @@ export function useTokenTracker (tokens) {
const [tokensWithBalances, setTokensWithBalances] = useState([])
const [error, setError] = useState(null)
const tokenTracker = useRef(null)
const memoizedTokens = useEqualityCheck(tokens)
const updateBalances = useCallback((tokenWithBalances) => {
setTokensWithBalances(tokenWithBalances)
@ -74,13 +76,13 @@ export function useTokenTracker (tokens) {
return
}
if (tokens.length === 0) {
if (memoizedTokens.length === 0) {
// sets loading state to false and token list to empty
updateBalances([])
}
buildTracker(userAddress, tokens)
}, [userAddress, teardownTracker, network, tokens, updateBalances, buildTracker])
buildTracker(userAddress, memoizedTokens)
}, [userAddress, teardownTracker, network, memoizedTokens, updateBalances, buildTracker])
return { loading, tokensWithBalances, error }
}