From 21200bc8d25ebda596c8137ff1b47b290a1a1f05 Mon Sep 17 00:00:00 2001 From: Jordan Sexton Date: Tue, 1 Nov 2022 13:42:27 -0600 Subject: [PATCH] Optimize `onError` (#640) * extract default onError prop value * Bikeshed the hell out of the error handling code * Rename var * Add changeset Co-authored-by: steveluscher --- .changeset/ninety-dolphins-change.md | 5 +++ .../core/react/src/WalletProviderBase.tsx | 35 +++++++++++-------- 2 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 .changeset/ninety-dolphins-change.md diff --git a/.changeset/ninety-dolphins-change.md b/.changeset/ninety-dolphins-change.md new file mode 100644 index 000000000..8694fc670 --- /dev/null +++ b/.changeset/ninety-dolphins-change.md @@ -0,0 +1,5 @@ +--- +'@solana/wallet-adapter-react': patch +--- + +Optimize `WalletProvider.onError` diff --git a/packages/core/react/src/WalletProviderBase.tsx b/packages/core/react/src/WalletProviderBase.tsx index a202f3449..54bf911d8 100644 --- a/packages/core/react/src/WalletProviderBase.tsx +++ b/packages/core/react/src/WalletProviderBase.tsx @@ -33,12 +33,7 @@ export function WalletProviderBase({ isUnloadingRef, onAutoConnectRequest, onConnectError, - onError = (error, adapter) => { - console.error(error, adapter); - if (error instanceof WalletNotReadyError && typeof window !== 'undefined' && adapter) { - window.open(adapter.url, '_blank'); - } - }, + onError, onSelectWallet, }: WalletProviderBaseProps) { const isConnectingRef = useRef(false); @@ -48,20 +43,30 @@ export function WalletProviderBase({ const [publicKey, setPublicKey] = useState(() => adapter?.publicKey ?? null); const [connected, setConnected] = useState(() => adapter?.connected ?? false); + /** + * Store the error handlers as refs so that a change in the + * custom error handler does not recompute other dependencies. + */ + const onErrorRef = useRef(onError); + useEffect(() => { + onErrorRef.current = onError; + return () => { + onErrorRef.current = undefined; + }; + }, [onError]); const handleErrorRef = useRef((error: WalletError, adapter?: Adapter) => { if (!isUnloadingRef.current) { - onError(error, adapter); + if (onErrorRef.current) { + onErrorRef.current(error, adapter); + } else { + console.error(error, adapter); + if (error instanceof WalletNotReadyError && typeof window !== 'undefined' && adapter) { + window.open(adapter.url, '_blank'); + } + } } return error; }); - useEffect(() => { - handleErrorRef.current = (error, adapter) => { - if (!isUnloadingRef.current) { - onError(error, adapter); - } - return error; - }; - }, [isUnloadingRef, onError]); // Wrap adapters to conform to the `Wallet` interface const [wallets, setWallets] = useState(() =>