-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathAppKitContext.tsx
More file actions
47 lines (39 loc) · 1.6 KB
/
AppKitContext.tsx
File metadata and controls
47 lines (39 loc) · 1.6 KB
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
import React, { createContext, useContext, useMemo, type ReactNode } from 'react';
import { AppKit } from './AppKit';
export interface AppKitContextType {
appKit: AppKit | null;
}
export const AppKitContext = createContext<AppKitContextType>({ appKit: null });
interface AppKitProviderProps {
children: ReactNode;
instance: AppKit;
}
export const AppKitProvider: React.FC<AppKitProviderProps> = ({ children, instance }) => {
return <AppKitContext.Provider value={{ appKit: instance }}>{children}</AppKitContext.Provider>;
};
export const useInternalAppKit = () => {
const context = useContext(AppKitContext);
if (context === undefined) {
throw new Error('useAppKit must be used within an AppKitProvider');
}
if (!context.appKit) {
// This might happen if the provider is rendered before AppKit is initialized
throw new Error('AppKit instance is not yet available in context.');
}
const stableFunctions = useMemo(() => {
if (!context.appKit) {
throw new Error('AppKit instance is not available');
}
return {
connect: context.appKit.connect.bind(context.appKit),
disconnect: context.appKit.disconnect.bind(context.appKit),
open: context.appKit.open.bind(context.appKit),
close: context.appKit.close.bind(context.appKit),
back: context.appKit.back.bind(context.appKit),
switchNetwork: context.appKit.switchNetwork.bind(context.appKit),
getProvider: context.appKit.getProvider.bind(context.appKit),
switchAccountType: context.appKit.switchAccountType.bind(context.appKit)
};
}, [context.appKit]);
return stableFunctions;
};