refactor: refuse empty strings

This commit is contained in:
Jaime Liz 2020-01-16 19:37:31 -06:00
parent d219ffa1ec
commit 100b86898f

View File

@ -22,7 +22,9 @@ const useCopyToClipboard = (): [CopyToClipboardState, (value: string) => void] =
return;
}
let noUserInteraction;
let normalizedValue;
try {
// only strings and numbers casted to strings can be copied to clipboard
if (typeof value !== 'string' && typeof value !== 'number') {
const error = new Error(`Cannot copy typeof ${typeof value} to clipboard, must be a string`);
if (process.env.NODE_ENV === 'development') console.error(error);
@ -33,7 +35,18 @@ const useCopyToClipboard = (): [CopyToClipboardState, (value: string) => void] =
});
return;
}
const normalizedValue = value.toString();
// empty strings are also considered invalid
else if (value === '') {
const error = new Error(`Cannot copy empty string to clipboard.`);
if (process.env.NODE_ENV === 'development') console.error(error);
setState({
value,
error,
noUserInteraction: true,
});
return;
}
normalizedValue = value.toString();
noUserInteraction = writeText(normalizedValue);
setState({
value: normalizedValue,
@ -42,7 +55,7 @@ const useCopyToClipboard = (): [CopyToClipboardState, (value: string) => void] =
});
} catch (error) {
setState({
value,
value: normalizedValue,
error,
noUserInteraction,
});