React
Un hook personalizado que inicializa el widget una vez al montar y vuelve a identificar al usuario cada vez que cambia la sesión.
El hook
hooks/usePriorityHunter.ts
// hooks/usePriorityHunter.ts
import { useEffect } from 'react';
declare global {
interface Window {
PH?: (cmd: string, payload?: unknown, cb?: () => void) => void;
PH_q?: unknown[][];
}
}
export function usePriorityHunter(widgetId: string, user?: {
id: string; email?: string; name?: string;
}) {
useEffect(() => {
if (typeof window === 'undefined') return;
if (document.getElementById('ph-embed-script')) return;
// Stub queue
if (!window.PH) {
window.PH = function(...args: unknown[]) {
((window.PH as any).q = (window.PH as any).q ?? []).push(args);
};
}
window.PH('init', { widgetId });
if (user) window.PH('identify', user);
const script = document.createElement('script');
script.id = 'ph-embed-script';
script.src = 'https://widget.priorityhunter.com/embed.js';
script.async = true;
document.head.appendChild(script);
return () => {
window.PH?.('destroy');
};
}, []);
// Re-identify when user changes
useEffect(() => {
if (user) window.PH?.('identify', user);
else window.PH?.('unidentify');
}, [user?.id]);
}app/layout.tsx
// app/layout.tsx (or any root component)
import { usePriorityHunter } from '@/hooks/usePriorityHunter';
export default function RootLayout() {
const { user } = useCurrentUser(); // your auth hook
usePriorityHunter('YOUR_WIDGET_ID', user
? { id: user.id, email: user.email, name: user.name }
: undefined
);
return <>{children}</>;
}✦
Devolver PH('destroy') en la limpieza del efecto garantiza que el widget se elimine si el componente se desmonta — útil para apps que renderizan condicionalmente un layout con el widget.
ℹ
Recuerda que la votación requiere identificación: pasa siempre el usuario al hook cuando haya sesión. Ver Identificar usuarios.
Siguiente: Next.js App Router →
Documentación de Priority Hunterpriorityhunter.com →