forked from Kewr-Tech-labs/cosmos-multisig-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppContext.tsx
77 lines (62 loc) · 2.45 KB
/
AppContext.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
75
76
77
import React, { useEffect, createContext, useContext, useReducer } from "react";
import { AppReducer, ChangeChainAction, initialState } from "./AppReducer";
import { ChainInfo } from "../types";
export interface AppContextType {
chain: ChainInfo;
}
const AppContext = createContext<{
state: AppContextType;
dispatch: React.Dispatch<ChangeChainAction>;
}>({ state: initialState, dispatch: () => {} });
function getChainInfoFromUrl(): ChainInfo {
const url = location.search;
const params = new URLSearchParams(url);
const chainInfo: ChainInfo = {
nodeAddress: decodeURIComponent(params.get("nodeAddress") || ""),
denom: params.get("denom") || "",
displayDenom: params.get("displayDenom") || "",
displayDenomExponent: parseInt(params.get("displayDenomExponent") || "", 10),
gasPrice: params.get("gasPrice") || "",
chainId: params.get("chainId") || "",
chainDisplayName: decodeURIComponent(params.get("chainDisplayName") || ""),
registryName: params.get("registryName") || "",
addressPrefix: params.get("addressPrefix") || "",
explorerLink: decodeURIComponent(params.get("explorerLink") || ""),
};
return chainInfo;
}
function setChainInfoParams(chainInfo: ChainInfo) {
const params = new URLSearchParams();
const keys = Object.keys(chainInfo) as Array<keyof ChainInfo>;
keys.forEach((value: keyof ChainInfo) => {
params.set(value, encodeURIComponent(chainInfo[value] || ""));
});
window.history.replaceState({}, "", `${location.pathname}?${params}`);
}
export function AppWrapper({ children }: { children: React.ReactNode }) {
let existingState;
if (typeof window !== "undefined") {
const storedState = localStorage.getItem("state");
if (storedState) {
existingState = JSON.parse(storedState);
}
const urlChainInfo = getChainInfoFromUrl();
// query params should override saved state
if (urlChainInfo.chainId) {
console.log("setting state from url");
existingState = { chain: urlChainInfo };
}
}
const [state, dispatch] = useReducer(AppReducer, existingState ? existingState : initialState);
const contextValue = { state, dispatch };
useEffect(() => {
if (state && state !== initialState) {
localStorage.setItem("state", JSON.stringify(state));
setChainInfoParams(state.chain);
}
}, [state]);
return <AppContext.Provider value={contextValue}>{children}</AppContext.Provider>;
}
export function useAppContext() {
return useContext(AppContext);
}