skip to Main Content

I am working with wagmi core in svelte and am looking to make a basic wallet connect and disconnect flow.

I am able to successfully connect by pressing the connect button, and having it call handleConnect.

    async function handleConnect() {
        await connect(config, { connector: injected() })
        const account = await getAccount(config)
        console.log(account)
    }

The console successfully shows an account.

After I do this, I can see my wallet has successfully connect.

enter image description here

However, upon refreshing, when checking the status of my connection, it says undefined when calling getAccount.

    onMount(async () => {
        const account = await getAccount(config)
        console.log(account)
    })

I get the following:

{address: undefined, addresses: undefined, chain: undefined, chainId: undefined, connector: undefined, …}

Why is that?

2

Answers


  1. Refreshing a webpage in the web browser is like restarting an ordinary program; all variables will be deleted, and then created anew. So it’s not unexpected that the previously created connection no longer exists.

    You can avoid this by storing state in cookies, or localStorage, etc., and then assign variables their values based on the stored state, but then you (or the library you are using) need to write the code doing this. In this case, it seems like the library doesn’t do this for you, so that is something you would need to do yourself.

    Login or Signup to reply.
  2. I would look into reconnect and creating a readable store that uses watchAccount. One approach would be to call reconnect after initiating your config.

    For example:

    // relevant imports
    
    // wagmi config
    
    export const account = readable(getAccount(config), set =>
      watchAccount(config, { onChange: set })
    )
    
    reconnect(config)
    
    export async function connect(
      type: ConnectorType,
      chainId: ConfiguredChainId | undefined
    ) {
      const connectors = config.connectors.filter(c => c.type === type)
      const connector = connectors[0] ?? connectors[1]
    
      if (connector) return _connect(config, { connector, chainId })
    }
    
    export const disconnect = () => {
      _disconnect(config)
    }
    

    Then in your svelte Connect.svelte component, use $ to react to the account store created above. Something like this:

    <script lang="ts">
      // relevant imports
    
      let connectError: any
      let walletAddress: Address
    
      $: if ($account.isConnected && $account.address) {
        walletAddress = $account.address
        connectError = undefined
      }
    </script>
    
    <!-- connect button component -->
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search