forked from solana-foundation/templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster-context.tsx
More file actions
61 lines (51 loc) · 1.54 KB
/
cluster-context.tsx
File metadata and controls
61 lines (51 loc) · 1.54 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
"use client";
import {
createContext,
useContext,
useState,
useCallback,
type ReactNode,
} from "react";
import type { ClusterMoniker } from "../lib/solana-client";
import { CLUSTERS } from "../lib/solana-client";
import { getExplorerUrl } from "../lib/explorer";
type ClusterContextValue = {
cluster: ClusterMoniker;
setCluster: (cluster: ClusterMoniker) => void;
getExplorerUrl: (path: string) => string;
};
const ClusterContext = createContext<ClusterContextValue | null>(null);
const STORAGE_KEY = "solana-cluster";
function getInitialCluster(): ClusterMoniker {
if (typeof window === "undefined") return "devnet";
const stored = localStorage.getItem(STORAGE_KEY);
if (stored && CLUSTERS.includes(stored as ClusterMoniker)) {
return stored as ClusterMoniker;
}
return "devnet";
}
export { CLUSTERS };
export function ClusterProvider({ children }: { children: ReactNode }) {
const [cluster, setClusterState] =
useState<ClusterMoniker>(getInitialCluster);
const setCluster = useCallback((c: ClusterMoniker) => {
setClusterState(c);
localStorage.setItem(STORAGE_KEY, c);
}, []);
const explorerUrl = useCallback(
(path: string) => getExplorerUrl(path, cluster),
[cluster]
);
return (
<ClusterContext.Provider
value={{ cluster, setCluster, getExplorerUrl: explorerUrl }}
>
{children}
</ClusterContext.Provider>
);
}
export function useCluster() {
const ctx = useContext(ClusterContext);
if (!ctx) throw new Error("useCluster must be used within ClusterProvider");
return ctx;
}