Files
penx/apps/web/lib/shared/useCopyToClipboard.ts
0xzio 3edfe1aebf refactor: use monorepo
fix: fix build

chore: update README

feat: init extension

fix: fix web build
2025-04-19 01:48:59 +08:00

44 lines
1022 B
TypeScript

import { useState } from 'react'
type CopiedValue = string | null
type CopyFn = (text: string) => Promise<boolean> // Return success
export function useCopyToClipboard() {
const [copiedText, setCopiedText] = useState<CopiedValue>(null)
const copy: CopyFn = async (text) => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported')
return false
}
// Try to save to clipboard then save it in the state if worked
try {
await navigator.clipboard.writeText(text)
setCopiedText(text)
return true
} catch (error) {
console.warn('Copy failed', error)
setCopiedText(null)
return false
}
}
return { copiedText, copy }
}
export const copy = async (text: string): Promise<boolean> => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported')
return false
}
try {
await navigator.clipboard.writeText(text)
return true
} catch (error) {
console.warn('Copy failed', error)
return false
}
}