This repository was archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathcontext.tsx
48 lines (39 loc) · 1.47 KB
/
context.tsx
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
import React, { useEffect, useState } from 'react'
import { Web3Storage } from 'web3.storage'
import { useChainContext } from '../chain/context';
import { useWeb3StorageToken } from '../utils/hooks';
import { ForumAPI } from './forum';
interface ApiContextInterface {
api: ForumAPI | undefined,
storageToken: string,
setStorageToken: (token: string) => void,
}
const ApiContext = React.createContext<ApiContextInterface>({
api: undefined,
storageToken: '',
setStorageToken: () => {},
})
export function useApiContext() {
return React.useContext(ApiContext)
}
export function ApiContextProvider(props: { children: React.ReactNode }) {
const { readonlyContract, authorizedContract } = useChainContext()
const [ storageToken, setStorageToken ] = useWeb3StorageToken()
const [api, setApi] = useState<ForumAPI | undefined>(undefined)
useEffect(() => {
if (!readonlyContract) {
setApi(undefined)
return
}
const storage = storageToken ? new Web3Storage({ token: storageToken }) : undefined
const forumAPI = new ForumAPI({ storage, readonlyContract, authorizedContract })
console.log('setting new forum api instance', forumAPI)
setApi(forumAPI)
}, [readonlyContract, authorizedContract, storageToken])
const context = { api, storageToken, setStorageToken }
return (
<ApiContext.Provider value={context}>
{props.children}
</ApiContext.Provider>
)
}