freighter
freighter copied to clipboard
Need a way to subscribe to network & account changes
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
andnetwork
arguments, maybe also anetworkDetails
(or, better, each key ofnetworkDetails
could be a separate key in the top level object) - returns void
- takes an object as an argument that has at least
What alternatives are there?
The heavy-handed polling workarounds that app authors need to use today
We should make sure this functionality works well with useSyncExternalStore
+1 on this
Implemented in v5.23.0