npm package: @saastoast/react-native
Description: SaasToast React Native SDK for simple event tracking
Author: SaasToast
Latest version: 1.0.1

# SaasToast React Native SDK

The official SaasToast SDK for React Native 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 Native

## Installation

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

## Quick Start

### 1. Using React Context (Recommended)

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

// 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: __DEV__, // Enable debug logging in development
      }}
    >
      <YourApp />
    </SaasToastProvider>
  );
}

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

  const handleButtonPress = async () => {
    const result = await track({
      type: 'button_pressed',
      metadata: {
        button_name: 'subscribe',
        screen: 'pricing',
      }
    });

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

  return (
    <TouchableOpacity onPress={handleButtonPress}>
      <Text>Track Event</Text>
    </TouchableOpacity>
  );
}
```

### 2. Using Client Directly

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

// 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: __DEV__,
  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: 'screen_view',
  metadata: {
    screen: 'Dashboard',
    previous_screen: 'Login',
  }
});
```

### 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: 'apple_pay',
    platform: Platform.OS,
  }
});
```

### Custom Event with Value

```tsx
await track({
  type: 'feature_used',
  userId: 'user_123',
  value: 10, // Custom scoring/importance value
  metadata: {
    feature: 'camera_capture',
    quality: 'high',
    duration_seconds: 30,
  }
});
```

## 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 Mobile App

```tsx
import React from 'react';
import { Platform } from 'react-native';
import { useSaasToast } from '@saastoast/react-native';

// Track product view
const ProductScreen = ({ productId, product }) => {
  const { track } = useSaasToast();

  useEffect(() => {
    track({
      type: 'product_viewed',
      userId: 'user_123',
      metadata: {
        product_id: productId,
        category: product.category,
        price: product.price,
        platform: Platform.OS,
        screen: 'ProductDetail',
      }
    });
  }, [productId, track]);

  const handleAddToCart = async () => {
    await track({
      type: 'add_to_cart',
      userId: 'user_123',
      value: 1,
      metadata: {
        product_id: productId,
        quantity: 1,
        price: product.price,
        platform: Platform.OS,
      }
    });
  };

  const handlePurchase = async (orderId: string, total: number) => {
    await track({
      type: 'purchase',
      userId: 'user_123',
      revenue: Math.round(total * 100), // Convert to cents
      currency: 'USD',
      metadata: {
        order_id: orderId,
        products: [productId],
        platform: Platform.OS,
        payment_method: Platform.OS === 'ios' ? 'apple_pay' : 'google_pay',
      }
    });
  };

  // Component UI...
};
```

### Social Media App

```tsx
// Track user interactions
const SocialFeedScreen = () => {
  const { track } = useSaasToast();

  const handlePostLike = async (postId: string) => {
    await track({
      type: 'post_liked',
      userId: 'user_123',
      metadata: {
        post_id: postId,
        screen: 'Feed',
        platform: Platform.OS,
      }
    });
  };

  const handleShare = async (postId: string, shareMethod: string) => {
    await track({
      type: 'post_shared',
      userId: 'user_123',
      metadata: {
        post_id: postId,
        share_method: shareMethod, // 'instagram', 'whatsapp', etc.
        screen: 'Feed',
        platform: Platform.OS,
      }
    });
  };

  const handleCommentCreate = async (postId: string, commentLength: number) => {
    await track({
      type: 'comment_created',
      userId: 'user_123',
      value: 1,
      metadata: {
        post_id: postId,
        comment_length: commentLength,
        platform: Platform.OS,
      }
    });
  };

  // Component UI...
};
```

### SaaS Mobile App

```tsx
// Track feature usage and subscriptions
const SubscriptionScreen = () => {
  const { track } = useSaasToast();

  const handleSubscriptionUpgrade = async (fromPlan: string, toPlan: string, price: number) => {
    await track({
      type: 'subscription_upgraded',
      userId: 'user_123',
      revenue: Math.round(price * 100), // Convert to cents
      currency: 'USD',
      value: 12, // Expected months
      metadata: {
        from_plan: fromPlan,
        to_plan: toPlan,
        billing_cycle: 'monthly',
        platform: Platform.OS,
        upgrade_screen: 'SubscriptionPlans',
      }
    });
  };

  const handleFeatureUsage = async (featureName: string) => {
    await track({
      type: 'feature_used',
      userId: 'user_123',
      metadata: {
        feature: featureName,
        platform: Platform.OS,
        app_version: '1.2.0',
      }
    });
  };

  // Component UI...
};
```

## Navigation Tracking

### React Navigation Integration

```tsx
import { NavigationContainer } from '@react-navigation/native';
import { useSaasToast } from '@saastoast/react-native';

function AppNavigator() {
  const { track } = useSaasToast();

  const onStateChange = (state) => {
    const currentScreen = getCurrentScreenName(state);

    track({
      type: 'screen_view',
      metadata: {
        screen: currentScreen,
        platform: Platform.OS,
        timestamp: new Date().toISOString(),
      }
    });
  };

  return (
    <NavigationContainer onStateChange={onStateChange}>
      {/* Your navigation structure */}
    </NavigationContainer>
  );
}

function getCurrentScreenName(state) {
  if (state?.routes?.[state.index]?.name) {
    return state.routes[state.index].name;
  }
  return 'Unknown';
}
```

## 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
}
```

## Platform-Specific Tracking

```tsx
import { Platform } from 'react-native';

// Add platform context to all events
const trackWithPlatform = (event) => {
  return track({
    ...event,
    metadata: {
      ...event.metadata,
      platform: Platform.OS,
      platform_version: Platform.Version,
      is_tablet: Platform.isPad || (Platform.OS === 'android' && /* your tablet detection logic */),
    }
  });
};

// Usage
await trackWithPlatform({
  type: 'app_opened',
  metadata: {
    app_version: '1.0.0',
  }
});
```

## TypeScript Support

The SDK is fully typed with TypeScript:

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

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

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

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.