Changeset View
Changeset View
Standalone View
Standalone View
lib/hooks/ens-cache.js
Show First 20 Lines • Show All 125 Lines • ▼ Show 20 Lines | invariant( | ||||
'the only way result can be falsey is if useENSNames is passed a ' + | 'the only way result can be falsey is if useENSNames is passed a ' + | ||||
'falsey input, and that can only happen if useStringForUser input is ' + | 'falsey input, and that can only happen if useStringForUser input is ' + | ||||
'falsey or isViewer is set', | 'falsey or isViewer is set', | ||||
); | ); | ||||
return user; | return user; | ||||
} | } | ||||
} | } | ||||
export { useENSNames, useENSName, useStringForUser }; | function useENSAvatar(ethAddress: ?string): ?string { | ||||
const cacheContext = React.useContext(ENSCacheContext); | |||||
const { ensCache } = cacheContext; | |||||
const cachedAvatar = React.useMemo(() => { | |||||
if (!ethAddress) { | |||||
return ethAddress; | |||||
} | |||||
if (!ensCache) { | |||||
return null; | |||||
} | |||||
return ensCache.getCachedAvatarURIForAddress(ethAddress); | |||||
}, [ensCache, ethAddress]); | |||||
const [ensAvatars, setENSAvatars] = React.useState< | |||||
$ReadOnlyMap<string, string>, | |||||
>(new Map()); | |||||
React.useEffect(() => { | |||||
if (!ensCache || !ethAddress || cachedAvatar !== undefined) { | |||||
return; | |||||
} | |||||
(async () => { | |||||
const result = await ensCache.getAvatarURIForAddress(ethAddress); | |||||
if (!result) { | |||||
return; | |||||
} | |||||
setENSAvatars(oldENSAvatars => { | |||||
const newENSAvatars = new Map(oldENSAvatars); | |||||
newENSAvatars.set(ethAddress, result); | |||||
return newENSAvatars; | |||||
}); | |||||
})(); | |||||
}, [ensCache, cachedAvatar, ethAddress]); | |||||
return React.useMemo(() => { | |||||
if (!ethAddress) { | |||||
return ethAddress; | |||||
} else if (cachedAvatar !== undefined) { | |||||
return cachedAvatar; | |||||
} else { | |||||
return ensAvatars.get(ethAddress); | |||||
} | |||||
}, [ethAddress, cachedAvatar, ensAvatars]); | |||||
} | |||||
export { useENSNames, useENSName, useStringForUser, useENSAvatar }; |