Skip to content

Commit

Permalink
[NO CHANGELOG][Checkout Widget] Notify iframe if widget was initialis…
Browse files Browse the repository at this point in the history
…ed with a provider (#2147)
  • Loading branch information
jhesgodi authored Sep 5, 2024
1 parent 7942f50 commit 4c4c891
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Checkout,
CheckoutWidgetConfiguration,
CheckoutWidgetParams,
PostMessageHandlerEventType,
} from '@imtbl/checkout-sdk';
import { Web3Provider } from '@ethersproject/providers';
import {
Expand All @@ -13,12 +14,13 @@ import {
import { CheckoutContextProvider } from './context/CheckoutContextProvider';
import { CheckoutAppIframe } from './views/CheckoutAppIframe';
import { getIframeURL } from './functions/iframeParams';
import { useMount } from './hooks/useMount';

export type CheckoutWidgetInputs = {
checkout: Checkout;
params: CheckoutWidgetParams;
config: CheckoutWidgetConfiguration;
provider?: Web3Provider
provider?: Web3Provider;
};

export default function CheckoutWidget(props: CheckoutWidgetInputs) {
Expand All @@ -37,20 +39,32 @@ export default function CheckoutWidget(props: CheckoutWidgetInputs) {
);
const checkoutReducerValues = useMemo(
() => ({
checkoutState: {
...checkoutState, iframeURL, checkout,
},
checkoutState: { ...checkoutState, iframeURL, checkout },
checkoutDispatch,
}),
[checkoutState, checkoutDispatch, iframeURL, checkout],
);

// If the widget was initialized with a provider,
// notify iframe via postMessage
const { postMessageHandler } = checkoutState;
useMount(
() => {
if (!provider) return;

postMessageHandler?.send(PostMessageHandlerEventType.PROVIDER_UPDATED, {
isMetamask: provider.provider.isMetaMask,
isPassport: (provider.provider as any)?.isPassport,
});
},
[postMessageHandler, provider] as const,
([_postMessageHandler]) => _postMessageHandler !== undefined,
);

// keep the provider updated in the state
useEffect(() => {
checkoutDispatch({
payload: {
type: CheckoutActions.SET_PROVIDER,
provider,
},
payload: { type: CheckoutActions.SET_PROVIDER, provider },
});
}, [provider]);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect, useRef } from 'react';

/**
* This hook is used to run an effect only once when after the component is mounted.
* and all dependencies are either by default not undefined or the compare function returns true.
*/
export const useMount = <T, D extends readonly T[]>(
effect: () => void,
deps: D,
compare?: (deps: D) => boolean,
) => {
const hasRunRef = useRef(false);

useEffect(() => {
const allDepsSatisfy = compare
? compare(deps)
: deps.every((dep) => dep !== undefined);
if (!hasRunRef.current && allDepsSatisfy) {
hasRunRef.current = true;
effect();
}
}, [deps, effect, compare]);
};

0 comments on commit 4c4c891

Please sign in to comment.