-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSdkContext.tsx
More file actions
68 lines (59 loc) · 1.82 KB
/
SdkContext.tsx
File metadata and controls
68 lines (59 loc) · 1.82 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import {
createContext,
PropsWithChildren,
useEffect,
useMemo,
useState,
useContext,
} from "react";
import { UniqueChain } from "@unique-nft/sdk";
import { useAccountsContext } from "../accounts/AccountsContext";
export type UniqueChainType = ReturnType<typeof UniqueChain>;
export type SdkContextValueType = {
sdk?: UniqueChainType;
};
/**
* React context for providing the Unique SDK instance throughout the application.
*
* @remarks
* This context allows any component in the application to access the initialized
* Unique SDK, enabling interaction with the Unique Network.
*/
export const SdkContext = createContext<SdkContextValueType>({
sdk: undefined,
});
export const baseUrl = process.env.REACT_APP_REST_URL || "";
/**
* A provider component that initializes the Unique SDK and supplies it via context to child components.
*
* @param children - The child components that will have access to the Unique SDK through the context.
* @returns A React component that provides the initialized Unique SDK to its children.
*
* @example
* ```tsx
* <SdkProvider>
* <App />
* </SdkProvider>
* ```
*/
export const SdkProvider = ({ children }: PropsWithChildren) => {
const [sdk, setSdk] = useState<UniqueChainType>();
const { selectedAccount } = useAccountsContext();
useEffect(() => {
if (selectedAccount) {
//@ts-expect-error wait update utils
const sdkInstance = UniqueChain({ baseUrl, account: selectedAccount });
setSdk(sdkInstance);
} else {
const sdkInstance = UniqueChain({ baseUrl });
setSdk(sdkInstance);
}
}, [selectedAccount]);
const sdkContextValue = useMemo(() => ({ sdk }), [sdk]);
return (
<SdkContext.Provider value={sdkContextValue}>
{children}
</SdkContext.Provider>
);
};
export const useSdkContext = () => useContext(SdkContext);