Skip to content

Commit

Permalink
Merge pull request #5 from GGAlanSmithee/feature/enable-usage-with-ssr
Browse files Browse the repository at this point in the history
Make the hook usable in a SSR setting
  • Loading branch information
MartinSchere authored Feb 11, 2024
2 parents a235e04 + 6c29326 commit 6e1be19
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect } from 'react';

import { State, useStore } from './store';
import { WalletName } from './typescript/cip30';

Expand Down Expand Up @@ -56,7 +57,7 @@ const useCardanoWallet = ({
connectWithStore(connectedWalletName, localStorageKey);
}, 10);
}
}, [autoConnect, localStorageKey, (window as any).cardano]);
}, [autoConnect, localStorageKey, connectWithStore]);

const connect = async (walletName: WalletName) => {
await connectWithStore(walletName, localStorageKey);
Expand Down
13 changes: 10 additions & 3 deletions src/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { bech32 } from 'bech32';
import cbor from 'cbor';
import produce from 'immer';
import create from 'zustand';

import { NetworkId, WalletApi, WalletName } from '../typescript/cip30';
import cbor from 'cbor';
import { fromHex } from '../utils';
import { bech32 } from 'bech32';

export type State = {
isConnected: boolean;
Expand Down Expand Up @@ -80,6 +81,12 @@ export const useStore = create<State>()((set, get) => ({
})
);
try {
// Exit early if the Cardano dApp-Wallet Web Bridge (CIP 30) has not been injected
// This can happen in a SSR scenario for example
if (typeof window === 'undefined' || !(window as any).cardano) {
throw Error('window.cardano is undefined');
}

const api: WalletApi = await (window as any).cardano[walletName].enable();
const [rawAddress] = await api.getUnusedAddresses();
const address = fromHex(rawAddress);
Expand All @@ -89,7 +96,7 @@ export const useStore = create<State>()((set, get) => ({
const words = bech32.toWords(address);

const bechAddr = bech32.encode(
address[0] == NetworkId.MAINNET ? 'addr' : 'addr_test',
address[0] === NetworkId.MAINNET ? 'addr' : 'addr_test',
words,
130
);
Expand Down

0 comments on commit 6e1be19

Please sign in to comment.