npm package: @saastoast/react
Description: Official React SDK for SaasToast analytics
Author: SaasToast Team
Latest version: 1.0.5

# SaasToast React SDK

The official SaasToast SDK for React applications, providing simple event tracking functionality.

## Features

- 🎯 **Simple Event Tracking** - Track custom events with metadata
- 📊 **Revenue Tracking** - Track purchases, subscriptions, and monetary events
- 🔒 **Type Safe** - Full TypeScript support
- ⚡ **Performance Optimized** - Minimal bundle size with automatic retries
- 📦 **Zero Dependencies** - No external dependencies beyond React

## Installation

```bash
npm install @saastoast/react
# or
yarn add @saastoast/react
```

## Quick Start

### 1. Using React Context (Recommended)

```tsx
import React from 'react';
import { SaasToastProvider, useSaasToast } from '@saastoast/react';

// Wrap your app with the provider
function App() {
  return (
    <SaasToastProvider
      config={{
        apiKey: 'api_live_your_api_key_here', // Get this from your SaasToast dashboard
        debug: true, // Enable debug logging in development
      }}
    >
      <YourApp />
    </SaasToastProvider>
  );
}

// Use the hook in your components
function MyComponent() {
  const { track } = useSaasToast();

  const handleButtonClick = async () => {
    const result = await track({
      type: 'button_clicked',
      metadata: {
        button_name: 'subscribe',
        page: 'pricing',
      }
    });

    if (result.success) {
      console.log('Event tracked:', result.eventId);
    }
  };

  return (
    <button onClick={handleButtonClick}>
      Track Event
    </button>
  );
}
```

### 2. Using Client Directly

```tsx
import { SaasToastClient } from '@saastoast/react';

// Create a client instance
const client = SaasToastClient.create('api_live_your_api_key_here');

// Or with custom configuration
const client = new SaasToastClient({
  apiKey: 'api_live_your_api_key_here',
  baseUrl: 'https://api.saastoast.com',
  debug: true,
  maxRetries: 3,
  timeout: 10000,
});

// Track an event
async function trackEvent() {
  const result = await client.track({
    type: 'user_signup',
    userId: 'user_123',
    metadata: {
      plan: 'premium',
      source: 'organic',
    }
  });

  if (result.success) {
    console.log('Event tracked:', result.eventId);
  } else {
    console.error('Failed to track event:', result.error);
  }
}
```

## Event Tracking

### Basic Event

```tsx
await track({
  type: 'page_view',
  metadata: {
    page: '/dashboard',
    referrer: document.referrer,
  }
});
```

### Revenue Event

```tsx
await track({
  type: 'purchase_completed',
  userId: 'user_123',
  revenue: 2999, // $29.99 in cents
  currency: 'USD',
  metadata: {
    product_id: 'prod_456',
    payment_method: 'stripe',
  }
});
```

### Custom Event with Value

```tsx
await track({
  type: 'feature_used',
  userId: 'user_123',
  value: 10, // Custom scoring/importance value
  metadata: {
    feature: 'export_data',
    format: 'csv',
  }
});
```

## Configuration Options

```typescript
interface SaasToastConfig {
  /** API key for authentication (required) */
  apiKey: string;

  /** Base URL for the API (default: 'https://api.saastoast.com') */
  baseUrl?: string;

  /** Maximum number of retry attempts (default: 3) */
  maxRetries?: number;

  /** Request timeout in milliseconds (default: 10000) */
  timeout?: number;

  /** Enable debug logging (default: false) */
  debug?: boolean;
}
```

## Event Interface

```typescript
interface Event {
  /** Event type identifier */
  type: string;

  /** User identifier */
  userId?: string;

  /** Revenue amount in cents */
  revenue?: number;

  /** Currency code (ISO 4217) */
  currency?: string;

  /** Event value for scoring/importance */
  value?: number;

  /** Custom properties */
  metadata?: Record<string, any>;

  /** Event timestamp (defaults to now) */
  timestamp?: Date | string;
}
```

## Response Interface

```typescript
interface TrackResponse {
  /** Whether the request was successful */
  success: boolean;

  /** Event ID from the server */
  eventId?: string;

  /** Error message if failed */
  error?: string;
}
```

## Examples

### E-commerce Tracking

```tsx
// Track product view
await track({
  type: 'product_viewed',
  userId: 'user_123',
  metadata: {
    product_id: 'prod_789',
    category: 'electronics',
    price: 299.99,
  }
});

// Track add to cart
await track({
  type: 'add_to_cart',
  userId: 'user_123',
  value: 1,
  metadata: {
    product_id: 'prod_789',
    quantity: 1,
    price: 299.99,
  }
});

// Track purchase
await track({
  type: 'purchase',
  userId: 'user_123',
  revenue: 29999, // $299.99 in cents
  currency: 'USD',
  metadata: {
    order_id: 'order_456',
    products: ['prod_789'],
    tax: 25.00,
    shipping: 10.00,
  }
});
```

### SaaS Application Tracking

```tsx
// Track feature usage
await track({
  type: 'feature_used',
  userId: 'user_123',
  metadata: {
    feature: 'api_key_generation',
    workspace: 'workspace_456',
  }
});

// Track subscription change
await track({
  type: 'subscription_upgraded',
  userId: 'user_123',
  revenue: 4999, // $49.99 monthly
  currency: 'USD',
  value: 12, // Expected months
  metadata: {
    from_plan: 'basic',
    to_plan: 'professional',
    billing_cycle: 'monthly',
  }
});
```

## Error Handling

The SDK handles errors gracefully and returns a response object:

```tsx
const result = await track({
  type: 'test_event',
  metadata: { test: true }
});

if (result.success) {
  console.log('Success! Event ID:', result.eventId);
} else {
  console.error('Failed:', result.error);
  // Handle the error appropriately
  // The SDK will have already retried based on your configuration
}
```

## TypeScript Support

The SDK is fully typed with TypeScript:

```tsx
import type { Event, SaasToastConfig, TrackResponse } from '@saastoast/react';

const config: SaasToastConfig = {
  apiKey: 'api_live_your_key',
  debug: true,
};

const event: Event = {
  type: 'user_action',
  userId: 'user_123',
  metadata: {
    action: 'clicked',
  },
};

const response: TrackResponse = await client.track(event);
```

## Support

- Documentation: [https://docs.saastoast.com](https://docs.saastoast.com)
- Issues: [GitHub Issues](https://github.com/saastoast/saastoast/issues)
- Email: support@saastoast.com

## License

MIT License - see LICENSE file for details.