watchChainId
Action for watching changes to the connected Starknet chain ID.
Import
import { watchChainId } from "starkweb/core";
Usage
index.ts
import { watchChainId } from "starkweb/core";
import { config } from "./config";
const unwatch = watchChainId(config, {
onChange(chainId, prevChainId) {
console.log('Chain changed:', chainId);
console.log('Previous chain:', prevChainId);
},
});
Parameters
import { type WatchChainIdParameters } from "starkweb/core";
onChange
(chainId: Hex, prevChainId: Hex) => void
Callback function that is called when the chain ID changes. Receives the new chain ID and previous chain ID as arguments.
index.ts
import { watchChainId } from "starkweb/core";
import { config } from "./config";
const unwatch = watchChainId(config, {
onChange(chainId, prevChainId) {
console.log('Chain changed:', chainId);
console.log('Previous chain:', prevChainId);
},
});
Return Type
import { type WatchChainIdReturnType } from "starkweb/core";
() => void
Function to stop watching for chain ID changes.
Example
example.ts
import { watchChainId } from "starkweb/core";
import { mainnet, testnet } from "starkweb/chains";
import { config } from "./config";
// Start watching chain ID changes
const unwatch = watchChainId(config, {
onChange(chainId, prevChainId) {
if (chainId === mainnet.chain_id) {
console.log('Switched to mainnet');
} else if (chainId === testnet.chain_id) {
console.log('Switched to testnet');
}
},
});
// Later: stop watching
unwatch();