forked from libp2p/universal-connectivity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx.tsx
74 lines (64 loc) · 1.71 KB
/
ctx.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import React, {
createContext,
useContext,
useState,
useEffect,
ReactNode,
} from 'react'
import type { Libp2p } from 'libp2p'
import { startLibp2p } from '../lib/libp2p'
import { ChatProvider } from './chat-ctx'
import { PeerProvider } from './peer-ctx'
import { ListenAddressesProvider } from './listen-addresses-ctx'
import { PubSub } from '@libp2p/interface-pubsub'
// 👇 The context type will be avilable "anywhere" in the app
interface Libp2pContextInterface {
libp2p: Libp2p<{ pubsub: PubSub }>
}
export const libp2pContext = createContext<Libp2pContextInterface>({
// @ts-ignore to avoid having to check isn't undefined everywhere. Can't be undefined because children are conditionally rendered
libp2p: undefined,
})
interface WrapperProps {
children?: ReactNode
}
let loaded = false
export function AppWrapper({ children }: WrapperProps) {
const [libp2p, setLibp2p] = useState<Libp2p<{ pubsub: PubSub }>>()
useEffect(() => {
const init = async () => {
if (loaded) return
try {
loaded = true
const libp2p = await startLibp2p()
// @ts-ignore
window.libp2p = libp2p
setLibp2p(libp2p)
} catch (e) {
console.error('failed to start libp2p', e)
}
}
init()
}, [])
if (!libp2p) {
return (
<div>
<h2>Initializing libp2p peer...</h2>
</div>
)
}
return (
<libp2pContext.Provider value={{ libp2p }}>
<ChatProvider>
<PeerProvider>
<ListenAddressesProvider>
{children}
</ListenAddressesProvider>
</PeerProvider>
</ChatProvider>
</libp2pContext.Provider>
)
}
export function useLibp2pContext() {
return useContext(libp2pContext)
}