1- import { createContext , useEffect , useMemo , useState } from "react" ;
1+ import { createContext , useEffect , useMemo , useRef , useState } from "react" ;
22import { wallet } from "../util/wallet" ;
33import storage from "../util/storage" ;
4+ import { useTransition } from 'react' ;
45
56export interface WalletContextType {
67 address ?: string ;
78 network ?: string ;
89 networkPassphrase ?: string ;
10+ isPending ?: boolean ;
11+ hasSyncedOnce ?: boolean
912} ;
1013
1114export const WalletContext = // eslint-disable-line react-refresh/only-export-components
1215 createContext < WalletContextType > ( { } ) ;
1316
1417export const WalletProvider = ( { children } : { children : React . ReactNode } ) => {
15- const [ address , setAddress ] = useState < string | undefined > (
16- ( ) => storage . getItem ( "walletAddress" ) ?? undefined
17- ) ;
18+ const [ address , setAddress ] = useState < string > ( ) ;
1819 const [ network , setNetwork ] = useState < string > ( ) ;
1920 const [ networkPassphrase , setNetworkPassphrase ] = useState < string > ( ) ;
21+ const [ isPending , startTransition ] = useTransition ( ) ;
22+ const [ hasSyncedOnce , setHasSyncedOnce ] = useState ( false ) ;
23+ const isFirstRun = useRef ( true ) ;
2024
2125 const nullify = ( ) => {
2226 setNetwork ( undefined )
@@ -25,6 +29,7 @@ export const WalletProvider = ({ children }: { children: React.ReactNode }) => {
2529 }
2630
2731 const updateCurrentWalletState = async ( ) => {
32+
2833 // There is no way, with StellarWalletsKit, to check if the wallet is
2934 // installed/connected/authorized. We need to manage that on our side by
3035 // checking our storage item.
@@ -69,6 +74,15 @@ export const WalletProvider = ({ children }: { children: React.ReactNode }) => {
6974 await new Promise ( ( res ) => {
7075 timer = setTimeout ( res , 1000 )
7176 } ) ;
77+ if ( isFirstRun . current ) {
78+ startTransition ( async ( ) => {
79+ await updateCurrentWalletState ( )
80+ setHasSyncedOnce ( true ) ;
81+ } ) ;
82+ isFirstRun . current = false ;
83+ } else {
84+ void updateCurrentWalletState ( ) ;
85+ }
7286 await updateCurrentWalletState ( )
7387 }
7488 } ) ( )
@@ -84,7 +98,9 @@ export const WalletProvider = ({ children }: { children: React.ReactNode }) => {
8498 address,
8599 network,
86100 networkPassphrase,
87- } ) , [ address , network , networkPassphrase ] ) ;
101+ isPending,
102+ hasSyncedOnce
103+ } ) , [ address , network , networkPassphrase , isPending , hasSyncedOnce ] ) ;
88104
89105 return (
90106 < WalletContext value = { contextValue } >
0 commit comments