useChain() switchNetwork bug

When called switchNetwork from the react useChain() when the network is unknown 2 things occur:

  1. The user is asked to add the network
  2. The user is asked to switch to the network

If during the add the use rejects then the switchNetwork returns a Promise.reject which is expected.
BUT, if the use adds the network and in step 2 cancels the switch, then the function throws a Promise.resolve which is NOT expected as the network didn’t switch.

I would use the chainId property from useChain() to verify but it seems to be inconsistent and not always reflect the selected chain in MetaMask if done manually outside of the Moralis SDK.

This is what the code looks like:

const { switchNetwork, chainId } = useChain();

return switchNetwork(POLYGON_CHAIN_ID).then(() => {
    // Expected: executed when the network was switched correctly
    // Actual: executed if the network was switched when previously existing AND if the network was not switched but only added during the process
}).catch((error) => {
    // Expect: executed if the network was not switched (both if previously existing or not )
    // Actual: executed only if the network previously existed and switch was cancelled
})

Hello can you please submit this here.

Cool thanks!

For anybody interested, here is the bug report: