Skip to content

Commit

Permalink
Store selected chain in localstorage
Browse files Browse the repository at this point in the history
  • Loading branch information
tumppi committed Nov 14, 2024
1 parent 03e0989 commit 6e01cbc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/Store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,7 +39,7 @@ interface Store {
}

const StoreContext = createContext<Store>({
chainId: POLYGON_CHAIN_ID,
chainId: DEFAULT_CHAIN_ID,
activeView: ActiveView.Map,
connectionsMode: ConnectionsMode.Auto,
displaySearchPhrase: '',
Expand All @@ -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()

Expand All @@ -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>(ActiveView.Map)

Expand Down Expand Up @@ -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])

Expand Down
2 changes: 2 additions & 0 deletions src/utils/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number, string> = {
[POLYGON_CHAIN_ID]: 'https://stream-metrics.streamr.network/api',
Expand Down

0 comments on commit 6e01cbc

Please sign in to comment.