Skip to content

Commit

Permalink
Optimize onError (#640)
Browse files Browse the repository at this point in the history
* extract default onError prop value

* Bikeshed the hell out of the error handling code

* Rename var

* Add changeset

Co-authored-by: steveluscher <[email protected]>
  • Loading branch information
jordaaash and steveluscher authored Nov 1, 2022
1 parent 0c41aca commit 21200bc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/ninety-dolphins-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@solana/wallet-adapter-react': patch
---

Optimize `WalletProvider.onError`
35 changes: 20 additions & 15 deletions packages/core/react/src/WalletProviderBase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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(() =>
Expand Down

0 comments on commit 21200bc

Please sign in to comment.