1
0
mirror of synced 2025-12-20 10:28:40 -05:00
Files
docs/components/hooks/useClipboard.ts
Mike Surowiec 06d8f81401 Two-pane Experiment (#21092)
* pull changes from docs-playground

* cleanup, add callout banner

* cleanup linting and test fixes

* add discussion link

Co-authored-by: James M. Greene <JamesMGreene@github.com>
2021-08-26 14:19:40 -04:00

42 lines
897 B
TypeScript

import { useState, useEffect } from 'react'
interface IOptions {
/**
* Reset the status after a certain number of milliseconds. This is useful
* for showing a temporary success message.
*/
successDuration?: number
}
export default function useCopyClipboard(
text: string,
options?: IOptions
): [boolean, () => Promise<void>] {
const [isCopied, setIsCopied] = useState(false)
const successDuration = options && options.successDuration
useEffect(() => {
if (isCopied && successDuration) {
const id = setTimeout(() => {
setIsCopied(false)
}, successDuration)
return () => {
clearTimeout(id)
}
}
}, [isCopied, successDuration])
return [
isCopied,
async () => {
try {
await navigator.clipboard.writeText(text)
setIsCopied(true)
} catch {
setIsCopied(false)
}
},
]
}