useClipboard Hook - Guida Utilizzo โ
๐ Descrizione โ
useClipboard() รจ un hook React per copiare testo negli appunti con feedback visivo automatico e gestione dello stato.
File: app/hooks/useClipboard.ts
๐ฏ Caratteristiche โ
โ
Hook React nativo - Integrazione perfetta con React components โ
Stato automatico - Gestisce copied, error automaticamente โ
Auto-reset - Resetta lo stato dopo timeout configurabile โ
Clipboard API moderna - HTTPS ready โ
Fallback automatico - Supporta HTTP e browser vecchi โ
Error handling - Gestione completa degli errori โ
TypeScript - Full type safety
๐ Utilizzo Base โ
Componente Simple โ
typescript
import { useClipboard } from "@/hooks/utils/useClipboard";
export function CopyButton() {
const { copy, copied } = useClipboard();
const handleCopy = async () => {
await copy("Testo da copiare", "CopyButton");
};
return (
<button onClick={handleCopy}>
{copied ? "โ
Copiato!" : "๐ Copia"}
</button>
);
}Con Error Handling โ
typescript
import { useClipboard } from "@/hooks/utils/useClipboard";
export function AdvancedCopy() {
const { copy, copied, error } = useClipboard(3000); // 3 secondi di timeout
const handleCopy = async () => {
const success = await copy("Testo", "AdvancedCopy");
if (!success && error) {
alert(`Errore: ${error}`);
}
};
return (
<div>
<button onClick={handleCopy}>Copia</button>
{copied && <span>โ
Copiato negli appunti!</span>}
{error && <span style={{color: 'red'}}>โ {error}</span>}
</div>
);
}๐ Signature Hook โ
typescript
export function useClipboard(resetTimeMs = 2000) {
// resetTimeMs: tempo (ms) prima di resettare lo stato 'copied'
// Default: 2000ms (2 secondi)
return {
copy, // (text: string, context?: string) => Promise<boolean>
copied, // boolean - true se il testo รจ stato copiato
error // string | null - messaggio di errore (se presente)
};
}Parametri โ
| Parametro | Tipo | Default | Descrizione |
|---|---|---|---|
resetTimeMs | number | 2000 | Millisecondi prima di resettare copied a false |
Ritorno โ
| Chiave | Tipo | Descrizione |
|---|---|---|
copy(text, context?) | async function | Funzione per copiare testo |
copied | boolean | true se ultimo copy รจ riuscito |
error | string | null | Messaggio errore (se presente) |
๐ก Esempi Pratici โ
1. Badge con Feedback โ
typescript
export function CopyWithBadge() {
const { copy, copied } = useClipboard();
return (
<button onClick={() => copy("Code123")}>
๐ {copied ? "โ
" : "Copy"}
</button>
);
}2. Multi-Copy โ
typescript
export function MultiCopy() {
const { copy, copied } = useClipboard(2000);
return (
<div>
<button onClick={() => copy("Fastlabel", "fastlabel")}>
Fastlabel {copied ? "โ
" : ""}
</button>
<button onClick={() => copy("Offline", "offline")}>
Offline {copied ? "โ
" : ""}
</button>
</div>
);
}3. Con Loader โ
typescript
import { useState } from "react";
import { useClipboard } from "@/hooks/utils/useClipboard";
export function CopyWithLoader() {
const { copy, copied, error } = useClipboard();
const [loading, setLoading] = useState(false);
const handleCopy = async () => {
setLoading(true);
await copy("Large text...", "loader");
setLoading(false);
};
return (
<button onClick={handleCopy} disabled={loading}>
{loading ? "Copiando..." : copied ? "โ
Copiato" : "๐ Copia"}
</button>
);
}4. Uso in Hook (useTopbarCart) โ
typescript
// Nel hook useTopbarCart
const { copy } = useClipboard();
const fastlabel = async () => {
const fastlabelText = iframeWindow.fastlabel_response;
const success = await copy(fastlabelText, "useTopbarCart");
if (success) {
notifySuccess();
}
};๐ Debug e Logging โ
L'hook logga automaticamente nel console:
[useClipboard] โ
Testo copiato negli appunti (Clipboard API)
[useClipboard] โ ๏ธ Clipboard API error: NotAllowedError
[useClipboard] โ
Testo copiato negli appunti (legacy method)๐ Troubleshooting โ
"Errore: Impossibile copiare negli appunti" โ
Cause comuni:
- Mancanza di permessi clipboard (browser chiede primo accesso)
- Ambiente non-HTTPS senza fallback disponibile
- Browser non supportato (molto raro)
Soluzione:
typescript
const { copy, error } = useClipboard();
await copy("text");
if (error) {
console.log(`Fallback usato: ${error}`);
}Copy non funziona in iframe โ
Possibili cause:
- CORS policy
- Same-origin requirement
Test:
typescript
// Controlla se รจ iframe
console.log(window !== window.parent);State non si resetta โ
Soluzione: Aumenta il timeout
typescript
const { copy, copied } = useClipboard(5000); // 5 secondi๐ Riferimenti Tecnici โ
Versione: 2.0.0 (Hook React) Ultima Aggiornamento: 2025-10-21