freighter icon indicating copy to clipboard operation
freighter copied to clipboard

Need a way to subscribe to network & account changes

Open chadoh opened this issue 1 year ago • 2 comments

What problem does your feature solve?

Right now, in order to have an app respond to a user's network & account changes in Freighter, an app needs to poll Freighter every X seconds. Example from the dependency used by Soroban's official dapp example: https://github.com/esteblock/soroban-react/blob/73f94af55d26f8ca42533af6c779998caeb3bb19/packages/core/src/SorobanReactProvider.tsx#L84-L127

What would you like to see?

A way to subscribe to network and account changes. Maybe it could be used like:

import { useEffect, useState } from 'react'
import { subscribeToChanges, getPublicKey, getNetwork } from '@stellar/freighter-api'

export function useFreighter() {
  const [publicKey, setPublicKey] = useState(null)
  const [network, setNetwork] = useState(null)

  useEffect(function initialLoad() {
    getPublicKey.then(setPublicKey)
    getNetwork.then(setNetwork)
  }, [])

  useEffect(function subscription() {
    return subscribeToChanges(({ publicKey: newPublicKey, network: newNetwork }) => {
      setPublicKey(newPublicKey)
      setNetwork(newNetwork)
    })
  }, [])

  return { publicKey, network }
}

Here we see that subscribeToChanges should:

  • return a function which allows unsubscribing
  • accept a function as an argument which
    • takes an object as an argument that has at least publicKey and network arguments, maybe also a networkDetails (or, better, each key of networkDetails could be a separate key in the top level object)
    • returns void

What alternatives are there?

The heavy-handed polling workarounds that app authors need to use today

chadoh avatar Jun 05 '23 18:06 chadoh

We should make sure this functionality works well with useSyncExternalStore

chadoh avatar Jun 14 '23 17:06 chadoh

+1 on this

GHesericsu avatar Jul 07 '23 02:07 GHesericsu

Implemented in v5.23.0

piyalbasu avatar Sep 24 '24 21:09 piyalbasu