-
Notifications
You must be signed in to change notification settings - Fork 22
/
useInbox.ts
67 lines (59 loc) · 1.83 KB
/
useInbox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { useCallback, useEffect } from 'react'
import { useSetRecoilState, waitForAll } from 'recoil'
import {
inboxItemsSelector,
refreshInboxItemsAtom,
} from '@dao-dao/state/recoil'
import { useCachedLoadingWithError } from '@dao-dao/stateless'
import { InboxState } from '@dao-dao/types'
import { useProfile } from './useProfile'
import { useOnWebSocketMessage } from './useWebSocket'
export const useInbox = (): InboxState => {
const { uniquePublicKeys } = useProfile()
const setRefresh = useSetRecoilState(refreshInboxItemsAtom)
const refresh = useCallback(() => setRefresh((id) => id + 1), [setRefresh])
// Refresh when any inbox items are added.
useOnWebSocketMessage(
uniquePublicKeys.loading
? []
: uniquePublicKeys.data.map(({ bech32Hash }) => `inbox_${bech32Hash}`),
'add',
refresh
)
// Refresh every minute.
useEffect(() => {
const interval = setInterval(() => refresh(), 60 * 1000)
return () => clearInterval(interval)
}, [refresh])
const itemsLoading = useCachedLoadingWithError(
!uniquePublicKeys.loading
? waitForAll(
uniquePublicKeys.data.map(({ bech32Hash, chains }) =>
inboxItemsSelector({
walletBech32Hash: bech32Hash,
fallbackChainId: chains[0].chainId,
})
)
)
: undefined,
(data) =>
data
.flat()
.sort((a, b) =>
a.timestamp && b.timestamp
? new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
: a.timestamp
? -1
: b.timestamp
? 1
: 0
)
)
return {
loading: itemsLoading.loading,
refreshing: itemsLoading.loading || !!itemsLoading.updating,
items:
itemsLoading.loading || itemsLoading.errored ? [] : itemsLoading.data,
refresh,
}
}