useCopy (SolidJS)

Copy text to your clipboard, and know when it's done so you can change the button's text to copied!.

typescriptjavascript
import type { Accessor } from 'solid-js'
import { createSignal } from 'solid-js'
 
export type UseCopyProps = {
  copiedTimeout?: number
}
 
type CopyFn = (text: string) => Promise<void>
 
export const useCopy = ({ copiedTimeout = 2000 }: UseCopyProps = {}): [
  copy: CopyFn,
  copied: Accessor<boolean>
] => {
  const [copied, setCopied] = createSignal(false)
  let timeout: NodeJS.Timeout
 
  const copy: CopyFn = async text => {
    await navigator.clipboard.writeText(text)
    setCopied(true)
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => setCopied(false), copiedTimeout)
  }
 
  return [copy, copied]
}
import { createSignal } from 'solid-js'
 
export const useCopy = ({ copiedTimeout = 2000 } = {}) => {
  const [copied, setCopied] = createSignal(false)
  let timeout
 
  const copy = async text => {
    await navigator.clipboard.writeText(text)
    setCopied(true)
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => setCopied(false), copiedTimeout)
  }
 
  return [copy, copied]
}

Check out the React version here.

Created 02/05/22Updated 27/08/22
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here