Skip to content

Commit ceb4548

Browse files
committed
refactor(ShareButton): Refactored duplicate call via setTimeout in favor of a reliable solution specific to my use-case
1 parent 7ee29f4 commit ceb4548

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

src/ShareButton.tsx

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,9 @@ interface CustomProps<LinkOptions> {
8181
openShareDialogOnClick?: boolean;
8282
opts: LinkOptions;
8383
/**
84-
* URL of the shared page
84+
* URL of the shared page, can be an async function that resolves a URL
8585
*/
86-
url: string;
86+
url: string | (() => Promise<string>);
8787
style?: React.CSSProperties;
8888
windowWidth?: number;
8989
windowHeight?: number;
@@ -92,7 +92,8 @@ interface CustomProps<LinkOptions> {
9292
* Takes a function that returns a Promise to be fulfilled before calling
9393
* `onClick`. If you do not return promise, `onClick` is called immediately.
9494
*/
95-
beforeOnClick?: () => Promise<void> | void;
95+
beforeOnClick?: () => void | Promise<void>;
96+
9697
/**
9798
* Takes a function to be called after closing share dialog.
9899
*/
@@ -132,20 +133,22 @@ export default class ShareButton<LinkOptions> extends Component<Props<LinkOption
132133
windowOpen(link, windowConfig, onShareWindowClose);
133134
};
134135

135-
handleClick = async (
136-
event: React.MouseEvent<HTMLButtonElement>,
137-
ignoreBeforeOnClick = false,
138-
): Promise<void> => {
136+
handleClick = async (event: React.MouseEvent<HTMLButtonElement>): Promise<void> => {
139137
const {
140138
beforeOnClick,
141139
disabled,
142140
networkLink,
143141
onClick,
144-
url,
145142
openShareDialogOnClick,
146143
opts,
147144
} = this.props;
148145

146+
let url = this.props.url;
147+
148+
if (typeof url == 'function') {
149+
url = await url();
150+
}
151+
149152
const link = networkLink(url, opts);
150153

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

155158
event.preventDefault();
156159

157-
if (beforeOnClick && !ignoreBeforeOnClick) {
158-
// Make the event object usuable in the following handleClick call
159-
event.persist();
160-
160+
if (beforeOnClick) {
161161
const returnVal = beforeOnClick();
162162

163163
if (isPromise(returnVal)) {
164164
await returnVal;
165165
}
166-
167-
// beforeOnClick could change our props, so let's re-run handleClick
168-
setTimeout(() => this.handleClick(event, true));
169-
return;
170166
}
171167

172168
if (openShareDialogOnClick) {

0 commit comments

Comments
 (0)