Skip to content

Commit

Permalink
refactor(ShareButton): Refactored duplicate call via setTimeout in fa…
Browse files Browse the repository at this point in the history
…vor of a reliable solution specific to my use-case
  • Loading branch information
Kashuab committed Jul 23, 2020
1 parent 7ee29f4 commit ceb4548
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/ShareButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ interface CustomProps<LinkOptions> {
openShareDialogOnClick?: boolean;
opts: LinkOptions;
/**
* URL of the shared page
* URL of the shared page, can be an async function that resolves a URL
*/
url: string;
url: string | (() => Promise<string>);
style?: React.CSSProperties;
windowWidth?: number;
windowHeight?: number;
Expand All @@ -92,7 +92,8 @@ interface CustomProps<LinkOptions> {
* Takes a function that returns a Promise to be fulfilled before calling
* `onClick`. If you do not return promise, `onClick` is called immediately.
*/
beforeOnClick?: () => Promise<void> | void;
beforeOnClick?: () => void | Promise<void>;

/**
* Takes a function to be called after closing share dialog.
*/
Expand Down Expand Up @@ -132,20 +133,22 @@ export default class ShareButton<LinkOptions> extends Component<Props<LinkOption
windowOpen(link, windowConfig, onShareWindowClose);
};

handleClick = async (
event: React.MouseEvent<HTMLButtonElement>,
ignoreBeforeOnClick = false,
): Promise<void> => {
handleClick = async (event: React.MouseEvent<HTMLButtonElement>): Promise<void> => {
const {
beforeOnClick,
disabled,
networkLink,
onClick,
url,
openShareDialogOnClick,
opts,
} = this.props;

let url = this.props.url;

if (typeof url == 'function') {
url = await url();
}

const link = networkLink(url, opts);

if (disabled) {
Expand All @@ -154,19 +157,12 @@ export default class ShareButton<LinkOptions> extends Component<Props<LinkOption

event.preventDefault();

if (beforeOnClick && !ignoreBeforeOnClick) {
// Make the event object usuable in the following handleClick call
event.persist();

if (beforeOnClick) {
const returnVal = beforeOnClick();

if (isPromise(returnVal)) {
await returnVal;
}

// beforeOnClick could change our props, so let's re-run handleClick
setTimeout(() => this.handleClick(event, true));
return;
}

if (openShareDialogOnClick) {
Expand Down

0 comments on commit ceb4548

Please sign in to comment.