|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | + |
| 3 | +interface RelevantResource { |
| 4 | + name: string |
| 5 | + url: string |
| 6 | + displayName: string |
| 7 | +} |
| 8 | + |
| 9 | +interface RelevantResourcesMap { |
| 10 | + [address: string]: RelevantResource[] |
| 11 | +} |
| 12 | + |
| 13 | +interface useTokenRelevantResourcesResult { |
| 14 | + data: RelevantResourcesMap | null |
| 15 | + error: string | null |
| 16 | + loading: boolean |
| 17 | +} |
| 18 | + |
| 19 | +const FAKE_TOKEN_RELEVANT_RESOURCES = { |
| 20 | + '0x03ab458634910aad20ef5f1c8ee96f1d6ac54919': [ |
| 21 | + { |
| 22 | + name: 'github', |
| 23 | + url: 'https://github.com/reflexer-labs/', |
| 24 | + displayName: 'Github', |
| 25 | + }, |
| 26 | + { |
| 27 | + name: 'website', |
| 28 | + url: 'https://reflexer.finance/', |
| 29 | + displayName: 'reflexer.finance', |
| 30 | + }, |
| 31 | + ], |
| 32 | + '0x0cec1a9154ff802e7934fc916ed7ca50bde6844e': [ |
| 33 | + { |
| 34 | + name: 'github', |
| 35 | + url: 'https://github.com/pooltogether/', |
| 36 | + displayName: 'Github', |
| 37 | + }, |
| 38 | + { |
| 39 | + name: 'website', |
| 40 | + url: 'https://pooltogether.com/', |
| 41 | + displayName: 'pooltogether.com', |
| 42 | + }, |
| 43 | + ], |
| 44 | +} |
| 45 | + |
| 46 | +const useTokenRelevantResources = (addresses: Set<string>): useTokenRelevantResourcesResult => { |
| 47 | + const [data, setData] = useState<RelevantResourcesMap | null>(null) |
| 48 | + const [error, setError] = useState<string | null>(null) |
| 49 | + const [loading, setLoading] = useState(false) |
| 50 | + |
| 51 | + const fetchRelevantResources = async (addresses: Set<string>): Promise<RelevantResourcesMap | void> => { |
| 52 | + const waitRandom = (min: number, max: number): Promise<void> => |
| 53 | + new Promise((resolve) => setTimeout(resolve, min + Math.round(Math.random() * Math.max(0, max - min)))) |
| 54 | + try { |
| 55 | + setLoading(true) |
| 56 | + setError(null) |
| 57 | + console.log('useTokenRelevantResources.fetchRelevantResources', addresses) |
| 58 | + await waitRandom(250, 2000) |
| 59 | + if (Math.random() < 0.05) { |
| 60 | + throw new Error('fake error') |
| 61 | + } |
| 62 | + return FAKE_TOKEN_RELEVANT_RESOURCES |
| 63 | + } catch (e) { |
| 64 | + setError('something went wrong') |
| 65 | + } finally { |
| 66 | + setLoading(false) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + useEffect(() => { |
| 71 | + setLoading(true) |
| 72 | + setError(null) |
| 73 | + fetchRelevantResources(addresses) |
| 74 | + .then((data) => { |
| 75 | + if (data) setData(data) |
| 76 | + }) |
| 77 | + .catch((e) => setError(e)) |
| 78 | + .finally(() => setLoading(false)) |
| 79 | + }, [addresses]) |
| 80 | + |
| 81 | + return { data, error, loading } |
| 82 | +} |
| 83 | + |
| 84 | +export default useTokenRelevantResources |
0 commit comments