npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

eventsforce-react-sdk

v1.1.1

Published

SDK oficial do EventsForce para React TypeScript - Rastreamento de eventos e analytics

Readme

🚀 EventsForce React SDK

SDK oficial do EventsForce para aplicações React TypeScript. Facilita a integração e tracking de eventos em suas aplicações React.

📦 Instalação

npm install @eventsforce/react-sdk
# ou
yarn add @eventsforce/react-sdk

🔧 Configuração

1. Provider Setup

Envolva sua aplicação com o EventsForceProvider:

import React from 'react';
import { EventsForceProvider } from '@eventsforce/react-sdk';
import App from './App';

const config = {
  apiKey: 'sua-api-key-aqui',
  baseUrl: 'https://api.eventsforce.com/api/v1', // opcional
  debug: process.env.NODE_ENV === 'development', // opcional
  userId: 'user123', // opcional
  userProperties: { // opcional
    plan: 'premium',
    country: 'BR'
  }
};

function Root() {
  return (
    <EventsForceProvider config={config}>
      <App />
    </EventsForceProvider>
  );
}

export default Root;

2. Uso Básico com Hooks

import React from 'react';
import { useEventsForce, usePageView, useButtonClick } from '@eventsforce/react-sdk';

function MyComponent() {
  const { track, identify, isReady } = useEventsForce();
  
  // Tracking automático de page view
  usePageView({
    properties: {
      section: 'dashboard'
    }
  });
  
  // Hook para tracking de cliques
  const trackClick = useButtonClick();
  
  const handleLogin = async () => {
    // Identificar usuário
    identify('user123', {
      name: 'João Silva',
      email: '[email protected]',
      plan: 'premium'
    });
    
    // Track evento customizado
    await track('user_login', {
      method: 'email',
      success: true
    });
  };
  
  const handleButtonClick = () => {
    trackClick('save_button', {
      location: 'header'
    });
  };
  
  if (!isReady) {
    return <div>Carregando...</div>;
  }
  
  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleButtonClick}>Salvar</button>
    </div>
  );
}

🎯 Hooks Disponíveis

useEventsForce()

Hook principal para acessar todas as funcionalidades:

const { track, identify, setUserProperties, reset, isReady } = useEventsForce();

// Tracking de evento
await track('purchase', {
  amount: 99.99,
  currency: 'BRL',
  product: 'premium_plan'
});

// Identificar usuário
identify('user123', {
  name: 'João',
  email: '[email protected]'
});

// Atualizar propriedades do usuário
setUserProperties({
  plan: 'enterprise',
  last_login: new Date().toISOString()
});

// Reset dos dados do usuário
reset();

usePageView(options)

Tracking automático de visualizações de página:

// Básico
usePageView();

// Com opções
usePageView({
  enabled: true,
  properties: {
    section: 'dashboard',
    feature: 'analytics'
  }
});

useButtonClick(options)

Hook para tracking de cliques em botões:

const trackClick = useButtonClick({
  eventName: 'button_click', // opcional
  properties: {
    page: 'dashboard'
  }
});

// Usar no onClick
<button onClick={() => trackClick('save_button')}>
  Salvar
</button>

useFormSubmit(options)

Hook para tracking de submissão de formulários:

const trackSubmit = useFormSubmit({
  formName: 'contact_form',
  onSuccess: (data) => console.log('Sucesso!', data),
  onError: (error) => console.error('Erro:', error)
});

const handleSubmit = async (formData) => {
  try {
    // Lógica de submissão
    const result = await submitForm(formData);
    await trackSubmit(true, result);
  } catch (error) {
    await trackSubmit(false, null, { error: error.message });
  }
};

useUserIdentification()

Hook para gerenciamento de usuários:

const { identifyUser, updateUserProperties, resetUser } = useUserIdentification();

// Identificar usuário
identifyUser('user123', {
  name: 'João',
  email: '[email protected]'
});

// Atualizar propriedades
updateUserProperties({
  last_activity: new Date().toISOString()
});

// Reset
resetUser();

useCustomEvent()

Hook para eventos customizados:

const trackEvent = useCustomEvent();

const handleCustomAction = () => {
  trackEvent('custom_action', {
    action_type: 'special',
    value: 42
  });
};

usePerformanceTracking()

Hook para tracking de performance:

const { startTimer, endTimer } = usePerformanceTracking();

const handleSlowOperation = async () => {
  startTimer('data_load');
  
  try {
    await loadData();
    endTimer('data_load', { success: true });
  } catch (error) {
    endTimer('data_load', { success: false, error: error.message });
  }
};

useErrorTracking()

Hook para tracking automático de erros:

const trackError = useErrorTracking();

// Tracking manual de erro
const handleError = (error) => {
  trackError(error, {
    component: 'MyComponent',
    action: 'data_fetch'
  });
};

// Erros JavaScript são trackados automaticamente

🌍 Uso Global (sem Context)

Para uso em componentes que não estão dentro do Provider:

import { initEventsForce, track, identify } from '@eventsforce/react-sdk';

// Inicializar uma vez na aplicação
initEventsForce({
  apiKey: 'sua-api-key-aqui',
  baseUrl: 'https://api.eventsforce.com/api/v1'
});

// Usar em qualquer lugar
await track('global_event', { test: true });
identify('user123', { name: 'João' });

📊 Eventos Pré-definidos

O SDK inclui métodos de conveniência para eventos comuns:

const eventsForce = useEventsForce();

// Page view
await eventsForce.pageView('/dashboard', {
  section: 'analytics'
});

// Clique em botão
await eventsForce.buttonClick('save_button', {
  location: 'header'
});

// Submissão de formulário
await eventsForce.formSubmit('contact_form', true, {
  fields_count: 5
});

// Compra
await eventsForce.purchase(99.99, 'BRL', {
  product: 'premium_plan',
  payment_method: 'credit_card'
});

// Busca
await eventsForce.search('analytics dashboard', 25, {
  category: 'features'
});

🔧 Configuração Avançada

Configuração Completa

const config = {
  apiKey: 'sua-api-key-aqui',
  baseUrl: 'https://api.eventsforce.com/api/v1',
  debug: true,
  userId: 'user123',
  userProperties: {
    name: 'João Silva',
    email: '[email protected]',
    plan: 'premium',
    country: 'BR',
    language: 'pt-BR'
  }
};

Propriedades Automáticas

O SDK adiciona automaticamente estas propriedades a todos os eventos:

  • user_agent: User agent do browser
  • page_url: URL atual da página
  • page_title: Título da página
  • timestamp: Timestamp do evento
  • Propriedades do usuário configuradas

🐛 Debug

Para ativar logs de debug:

const config = {
  apiKey: 'sua-api-key-aqui',
  debug: true // Ativa logs no console
};

📝 TypeScript

O SDK é totalmente tipado. Tipos principais:

interface EventsForceConfig {
  apiKey: string;
  baseUrl?: string;
  debug?: boolean;
  userId?: string;
  userProperties?: Record<string, any>;
}

interface EventProperties {
  [key: string]: any;
}

interface UserProperties {
  [key: string]: any;
}

🚀 Exemplos Práticos

E-commerce

function ProductPage({ product }) {
  const { track } = useEventsForce();
  
  usePageView({
    properties: {
      page_type: 'product',
      product_id: product.id,
      category: product.category
    }
  });
  
  const handleAddToCart = () => {
    track('add_to_cart', {
      product_id: product.id,
      product_name: product.name,
      price: product.price,
      currency: 'BRL'
    });
  };
  
  const handlePurchase = () => {
    track('purchase', {
      product_id: product.id,
      amount: product.price,
      currency: 'BRL',
      payment_method: 'credit_card'
    });
  };
  
  return (
    <div>
      <h1>{product.name}</h1>
      <button onClick={handleAddToCart}>Adicionar ao Carrinho</button>
      <button onClick={handlePurchase}>Comprar Agora</button>
    </div>
  );
}

Dashboard Analytics

function Dashboard() {
  const { track } = useEventsForce();
  const trackClick = useButtonClick();
  
  usePageView({
    properties: {
      page_type: 'dashboard',
      user_role: 'admin'
    }
  });
  
  const handleExportData = () => {
    trackClick('export_data', {
      format: 'csv',
      date_range: '30_days'
    });
  };
  
  const handleFilterChange = (filter) => {
    track('filter_applied', {
      filter_type: filter.type,
      filter_value: filter.value,
      page: 'dashboard'
    });
  };
  
  return (
    <div>
      <h1>Dashboard</h1>
      <button onClick={handleExportData}>Exportar Dados</button>
    </div>
  );
}

📄 Licença

MIT License - veja o arquivo LICENSE para detalhes.

🤝 Contribuição

Contribuições são bem-vindas! Por favor, abra uma issue ou pull request.

📞 Suporte

  • 📧 Email: [email protected]
  • 📖 Documentação: https://docs.eventsforce.com
  • 🐛 Issues: https://github.com/eventsforce/react-sdk/issues