From 6e01cbc56e9868a067543d5a3164bdb636a400ff Mon Sep 17 00:00:00 2001 From: Tuomas Koponen <432588+tumppi@users.noreply.github.com> Date: Thu, 14 Nov 2024 09:09:34 +0200 Subject: [PATCH] Store selected chain in localstorage --- src/Store.tsx | 21 ++++++++++++++++++--- src/utils/chains.ts | 2 ++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Store.tsx b/src/Store.tsx index 4417e74..4000627 100644 --- a/src/Store.tsx +++ b/src/Store.tsx @@ -17,7 +17,7 @@ import { ActiveView, ConnectionsMode, OperatorNode } from './types' import { useHud } from './utils' import { useOperatorNodesForStreamQuery } from './utils/nodes' import { truncate } from './utils/text' -import { POLYGON_CHAIN_ID } from './utils/chains' +import { DEFAULT_CHAIN_ID, SUPPORTED_CHAIN_IDS } from './utils/chains' interface Store { chainId: number @@ -39,7 +39,7 @@ interface Store { } const StoreContext = createContext({ - chainId: POLYGON_CHAIN_ID, + chainId: DEFAULT_CHAIN_ID, activeView: ActiveView.Map, connectionsMode: ConnectionsMode.Auto, displaySearchPhrase: '', @@ -61,6 +61,9 @@ interface StoreProviderProps { children?: ReactNode } +// Add a constant for the storage key +const CHAIN_ID_STORAGE_KEY = 'network-explorer-chain-id' + export function StoreProvider(props: StoreProviderProps) { const selectedNode = useNodeByNodeIdParam() @@ -77,7 +80,17 @@ export function StoreProvider(props: StoreProviderProps) { }) }) - const [chainId, setChainId] = useState(POLYGON_CHAIN_ID) + // Initialize chainId from localStorage + const [chainId, setChainId] = useState(() => { + const stored = localStorage.getItem(CHAIN_ID_STORAGE_KEY) + + // Check if the stored value is a valid network chainId + if (stored && SUPPORTED_CHAIN_IDS.includes(parseInt(stored, 10))) { + return parseInt(stored, 10) + } + + return DEFAULT_CHAIN_ID + }) const [activeView, setActiveView] = useState(ActiveView.Map) @@ -106,7 +119,9 @@ export function StoreProvider(props: StoreProviderProps) { [showConnections], ) + // Persist chainId changes useEffect(() => { + localStorage.setItem(CHAIN_ID_STORAGE_KEY, chainId.toString()) console.log('Store: Chain ID changed:', chainId) }, [chainId]) diff --git a/src/utils/chains.ts b/src/utils/chains.ts index eb6cd61..ee64198 100644 --- a/src/utils/chains.ts +++ b/src/utils/chains.ts @@ -2,6 +2,8 @@ import { config } from '@streamr/config' export const POLYGON_CHAIN_ID = config.polygon.id export const POLYGON_AMOY_CHAIN_ID = config.polygonAmoy.id +export const DEFAULT_CHAIN_ID = POLYGON_CHAIN_ID +export const SUPPORTED_CHAIN_IDS = [POLYGON_CHAIN_ID, POLYGON_AMOY_CHAIN_ID] const INDEXER_URLS: Record = { [POLYGON_CHAIN_ID]: 'https://stream-metrics.streamr.network/api',