-
Notifications
You must be signed in to change notification settings - Fork 22
/
useDaoClient.ts
60 lines (52 loc) · 1.4 KB
/
useDaoClient.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
import { useQueryClient } from '@tanstack/react-query'
import { useMemo } from 'react'
import { useDaoIfAvailable } from '@dao-dao/stateless'
import { DaoSource, IDaoBase } from '@dao-dao/types'
import { getDao } from '../clients/dao'
export type UseDaoClientOptions = {
/**
* DAO to fetch the client for. If undefined, uses the current DAO context.
* Otherwise, throws an error.
*/
dao?: DaoSource
}
export type UseDaoClientReturn = {
/**
* DAO client.
*/
dao: IDaoBase
}
/**
* Hook to get or create a DAO client. It will not be initialized.
*/
export const useDaoClient = ({
dao: daoSource,
}: UseDaoClientOptions): UseDaoClientReturn => {
const queryClient = useQueryClient()
const currentDao = useDaoIfAvailable()
// Get DAO client. If matches current DAO context, use that one instead.
const dao = useMemo(
() =>
currentDao &&
(!daoSource ||
(currentDao.chainId === daoSource.chainId &&
currentDao.coreAddress === daoSource.coreAddress))
? currentDao
: daoSource
? getDao({
queryClient,
chainId: daoSource.chainId,
coreAddress: daoSource.coreAddress,
})
: undefined,
[currentDao, daoSource, queryClient]
)
if (!dao) {
throw new Error(
'Cannot use useDaoClient hook with no DAO provided and when not in a DAO context.'
)
}
return {
dao,
}
}